谭浩强C++课后习题35——复数加法(可运算整数)
题目描述:定义一个复数类,重载运算符“+”,使之能用于复数的假发运算。参与运算的两个运算量可以都是类对象,也可以其中一个是整数。
解题思路:可以重载三次运算符,使之可以计算整数+复数,复数+复数,复数+整数;也可以写一个类似于强制转换的转换构造函数。
#include<iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r, double i) :real(r), imag(i) {}
Complex(int r) :real(r), imag(0) {}
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();cout << endl;
int num = 5;
Complex c3 = Complex(num);
c1.show();cout << "+" << num << "=";(c1 + c3).show();
return 0;
}
运行测试结果: