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

本文详细介绍了如何在C++中使用友元函数来重载位移操作符<<和>>,以实现自定义类型的数据输入输出。通过友元函数,可以访问类的私有和保护成员,从而方便地定制输入输出的行为。
摘要由CSDN通过智能技术生成
#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;
	
}
*/
//链式编程返回值不能是void ,需要返回一个引用


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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值