c++输入重载&输出重载

首先,我们需要清楚,输入输出重载必须作为全局函数,而不能作为类内声明的函数,所以在类内声明重载函数的时候需要使用友元函数的形式。

#include <iostream>
class test
{
public:
	test(int x = 0, int y = 0)	//构造函数
	{
		a = x;
		b = y;
	}

	~test(){}
	friend std::istream &operator>>(std::istream &in, test &x);
	friend std::ostream &operator<<(std::ostream &out, test &x);

protected:
	int a;
	int b;	
};

std::istream &operator>>(std::istream &in, test &x)
{
	in >> x.a >> x.b;
	return in;
}

std::ostream &operator<<(std::ostream &out, test &x)
{
	out << x.a << " " << x.b;
	return out;
}
int main()
{

	test A(3,4);
	std::cin >> A;
	std::cout << A <<std::endl;
	return 0;
}
上述程序实现简单的输入两个数字,输出两个数字的功能
输入:1 2
输出:1 2

很多情况下,为了保证程序的多态性,常常会用到模板函数,当用到类模板的时候一定要注意。虽然重载函数在类内声明,但其并不属于该类,所以重载函数声明时的参数也同样需要使用模板函数。

template <typename T>
class test
{
public:
	test(T x = 0, T y = 0)	//构造函数
	{
		a = x;
		b = y;
	}
	~test(){}
	template <typename U>
	friend std::istream &operator>>(std::istream &in, test<U> &x);
	template <typename U>
	friend std::ostream &operator<<(std::ostream &out, test<U> &x);

protected:
	T a;
	T b;	
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值