前言
实现的模板类中,如果要打印输出实时的私有成员内容,重载operator<<就可并设为友元即可。
友元不仅让其能够访问类内成员。而且使其成为普通函数,而不是类的成员函数。如过不加friend,就需要用对象来调用。
operator<<也需要泛型,就将其也做成模板函数,再在类外实现即可。
实例
代码如下(示例):
用栈实现一个队列,队列是私有的。这个类是模板类。
通过设定友元,使得(非成员重载运算符operator<<)能够访问到对象中私有成员。
template<typename TT>
class MyQueue {
private:
stack<TT> mystack;
public:
MyQueue() {
}
//*************************************//
template<typename T>
friend ostream &operator<<(ostream &os, MyQueue<T> temp);
//*************************************//
void push(TT x) {
stack<TT> mystack2;
while (!mystack.empty())
{
mystack2.push(mystack.top());
mystack.pop();
}
mystack.push(x);
while (!mystack2.empty())
{
mystack.push(mystack2.top());
mystack2.pop();
}
}
/** Removes the element from in front of queue and returns that element. */
TT pop() {
TT temp = mystack.top();
mystack.pop();
return temp;
}
/** Get the front element. */
TT peek() {
return mystack.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return mystack.empty();
}
};
//*************************************//
template<typename T>
ostream &operator<<(ostream &os, MyQueue<T> temp) {
while (!temp.mystack.empty())
{
os << "" << temp.mystack.top();
temp.mystack.pop();
}
return os;
}
//*************************************//
void main()
{
MyQueue<string> my_queue;
my_queue.push("he");
my_queue.push("llo");
cout << "\n now: " << my_queue << endl;
my_queue.push(" word");
my_queue.push(" ss");
cout << "\n now: " << my_queue << endl;
MyQueue<int> my_queue2;
my_queue2.push(1);
my_queue2.push(2);
cout << "\n now: " << my_queue2 << endl;
my_queue2.push(3);
my_queue2.push(4);
cout << "\n now: " << my_queue2 << endl;
}
效果
参考
C++ primer plus
https://blog.youkuaiyun.com/u012501459/article/details/44175915