谭浩强C++课后习题34——复数相加(运算符重载)

谭浩强C++课后习题34——复数相加(运算符重载)

题目描述:定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。将运算符函数重载,求两个复数之和。

#include<iostream>
using namespace std;
class Complex {
private:
	double real;
	double imag;
public:
	Complex(double r, double i) :real(r), imag(i) {}
	void show() { cout << "(" << real << "," << imag << "i)" ; }
	friend Complex operator+(Complex& c1, Complex& c2);
};
Complex operator+(Complex& c1, Complex& c2)
{
	return Complex(c1.real + c2.real, c1.imag + c2.imag);
}
int main() {
	Complex c1(3, 4);
	Complex c2(5, -10);
	c1.show();
	cout << "+";
	c2.show();
	cout << "=";
	(c1 + c2).show();
	return 0;
}

运行测试结果:
在这里插入图片描述

发布了35 篇原创文章 · 获赞 35 · 访问量 564

猜你喜欢

转载自blog.csdn.net/weixin_45295612/article/details/105311693