Chen_Ge_ 2021-03-31 10:43 采纳率: 100%
浏览 43
已采纳

c++重载输出流运算符

#include <iostream>
using namespace std;
class CComplex {
public:
	CComplex();
	CComplex(double x, double y);
	CComplex(double R);
	friend CComplex operator + (CComplex& obj1, CComplex& obj2);
	friend CComplex operator - (CComplex& obj1, CComplex& obj2);
	friend CComplex operator * (CComplex& obj1, CComplex& obj2);
	friend CComplex operator / (CComplex& obj1, CComplex& obj2);
	friend ostream& operator << (ostream& output, CComplex& C);
private:
	double real;
	double imag;
};

CComplex::CComplex() {
	real = 0.0;
	imag = 0.0;
}
CComplex::CComplex(double x, double y) {
	real = x;
	imag = y;
}
CComplex::CComplex(double R) {
	real = R;
	imag = 0;
}

CComplex operator + (CComplex& obj1, CComplex& obj2) {
	CComplex obj3(obj1.real + obj2.real, obj1.imag + obj2.imag);
	return obj3;
}
CComplex operator - (CComplex& obj1, CComplex& obj2) {
	CComplex obj3(obj1.real - obj2.real, obj1.imag - obj2.imag);
	return obj3;
}
CComplex operator * (CComplex& obj1, CComplex& obj2) {
	CComplex obj3(obj1.real * obj2.real - obj1.imag * obj2.imag, obj1.real * obj2.imag - obj2.real * obj1.imag);
	return obj3;
}
CComplex operator / (CComplex& obj1, CComplex& obj2) {
	if (obj2.real == 0 && obj2.imag == 0) { cout << "Wrong!" << endl; exit(0); }
	CComplex obj3((obj1.real * obj2.real - obj1.imag * (-obj2.imag)) / (obj2.real * obj2.real + obj2.imag * obj2.imag),
		obj1.real * (-obj2.imag) - obj2.real * obj1.imag / (obj2.real * obj2.real + obj2.imag * obj2.imag));
	return obj3;
}
ostream& operator << (ostream& output, CComplex& C) {
	output << C.real << " + " << C.imag << "i";
	return output;
}

int main()
{
	CComplex c1 = 5;
	CComplex c2 = 0;
	CComplex c3 = CComplex(3, 4);
	cout << c1 << endl;
	cout << c2 << endl;
	cout << c3 << endl;

	CComplex c4 = c1 + c3;
	cout << c4 << endl;
	CComplex c5 = c1 - c3;
	cout << c5 << endl;
	CComplex c6 = c1 * c3;
	cout << c6 << endl;
	CComplex c7 = c1 / c3;
	cout << c7 << endl;
	//cout << ( c1 + c3 ) << endl;
	//cout << c1 + c3 << endl;
	return 0;
}
/*
提问:
1.为什么71,72行会报错;
*/
  • 写回答

2条回答 默认 最新

  • 502203305 2021-03-31 10:58
    关注

    重载运算符使用 const CComplex&类型,报错是因为传入是一个临时的消亡值.需要用const的方式延长生命周期.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 pyqt5读取ui文件报错
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?