C++模板类;友元重载operator<<,使其也具有泛型特性; 非成员重载运算符的模板。


前言

实现的模板类中,如果要打印输出实时的私有成员内容,重载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++函数模板、类模板

C++ primer plus

https://blog.csdn.net/u012501459/article/details/44175915

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值