1、完成“+”、“-”、“++”重载编程任务;
代码
#include<iostream>
using namespace std;
class Complex
{
public:
double real, imag;
Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) {};
Complex operator-(const Complex& c);
Complex operator++(int n);
~Complex() {};
private:
};
Complex Complex::operator ++(int n)//参数只能是int n;
{
cout << "operator ++" << endl;
Complex temp = *this;
(this->real)++;
return temp;
}
Complex operator+(const Complex& a, const Complex& b)
{
cout << "operator +" << endl;
return Complex(a.real + b.real, a.imag + b.imag);
}
Complex Complex::operator-(const Complex& c)
{
cout << "operator -" << endl;
return Complex(real - c.real, imag - c.imag);
}
int main() {
Complex a(4, 4), b(1, 1), c;
c = a + b;
cout << "a+b = ";
cout << c.real << "," << c.imag << endl;
c = a - b;
cout << "a-b = ";
cout << c.real << "," << c.imag << endl;
a++;
cout << "a++ ";
cout << a.real << "," << a.imag<< endl;
}
运行结果
