首先,我们需要清楚,输入输出重载必须作为全局函数,而不能作为类内声明的函数,所以在类内声明重载函数的时候需要使用友元函数的形式。
#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;
};