C++之运算符重载(二)

运算符重载的内容非常多。这篇续写上一篇的。上一篇的地址如下:

https://blog.csdn.net/zy010101/article/details/105240318

这篇讲述使用友元函数重载输入输出运算符。C++提供的输入输出流是std空间中的cout,cin,cerr对象。他们分别是输入,输出,出错。我们想要重载 << 和 >>只能是使用友元函数重载。不能重载为成员函数,因为我们无法给输入输出流的代码加上成员函数。

#include<iostream>
using namespace std;

class Complex
{
private:
	int a;
	int b;
public:
	Complex(int x = 0, int y = 0);
	//重载输入>>
	friend std::istream& operator>>(std::istream& input, Complex& c)
	{
		input >> c.a >> c.b;
		return input;
	}
	//重载输出<<
	friend ostream& operator<<(ostream& out, const Complex& c)
	{
		out << c.a << "+" << c.b << "i" << std::endl;
		return out;
	}

};


Complex::Complex(int x, int y):a(x),b(y)
{
}


int main()
{
	Complex c(1, 1);

	std::cout << c;			//输出c

	std::cin >> c;			//输入c

	std::cout << c;			//输出c

	return 0;
}

测试结果如下:

说明我们的运算符重载没有问题。

其实也可以重载为成员函数,但是这样使用的标准输入,标准输出,标准出错就不是cout,cin,cerr了,而是你自己定义的流对象了。这样不利于维护。

 

发布了222 篇原创文章 · 获赞 174 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/zy010101/article/details/105245007