P213_友元函数实现左移右移操作符重载

#include<iostream>
using namespace std;
class Complex
{
	friend Complex operator+(Complex &c1, Complex &c2);
	friend ostream& operator<<(ostream &out, Complex &c1);

private:
	int a;
	int b;
public:
	Complex(int a = 0, int b = 0)
	{
		this->a = a;
		this->b = b;
	}
	void printCom()
	{
		cout << a << "+" << b << "i" << endl;
	}
	//成员函数 法 实现 - 运算符重载
	Complex operator-(Complex &c2)
	{
		Complex tmp(this->a - c2.a, this->b - c2.b);
		return tmp;
	}
};


/*
void operator<<(ostream &out, Complex &c1)
{
	out << c1.a << "+" << c1.b << "i" << endl;
	
}
*/


ostream & operator<<(ostream &out, Complex &c1)
{
	out << c1.a << "+" << c1.b <<"i"<< endl;
	return out;
}

int main()
{
	int a = 10;
	Complex c1(1, 2), c2(3,4);
	cout << a << endl;  //按照数据类型

	//1
	cout << c1;

	//2  函数返回值当左值  需要返回一个引用
	//cout.operator (c1);
	//应该在cout类中,添加 成员函数 .operator<<
	//结论:输入输出流的重载只能使用友元函数的方法,不能使用成员函数的方法

	//3 连体输出
	cout << c1 << "aadddd";

	//cout.operator(c1).operator<<("aadddd");
	//void .operator<<("aadddd");  左操作数为void
	//




	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41983807/article/details/87825336
今日推荐