【C++】运算符重载练习内容

为复数重载+、-运算符,编程实现(6+7i)+(7+8i)和(6+7i)-(7+8i)的运算。

#include
using namespace std;
class Complex {
public: 
	Complex(double r = 0.0, double i = 0.0) :real(r), imag(i) {}
	Complex operator+ (Complex &c2);// 运算符“+”重载为成员函数
	Complex operator- (Complex &c2);// 运算符“-”重载为成员函数 
	//friend Complex operator+ (Complex &c1, Complex &c2);// 运算符“+”重载为友元函数
	//friend Complex operator- (Complex &c1, Complex &c2);// 运算符“-”重载为友元函数 
	void display();
private: 
	double real, imag;
};

Complex Complex::operator+(Complex &c2) { 
	Complex c1; 
	c1.real = real + c2.real;
	c1.imag = imag + c2.imag;
	return c1;
}

Complex Complex::operator-(Complex &c2) {
	Complex c1;
	c1.real = real - c2.real;
	c1.imag = imag - c2.imag;
	return c1;
}

void Complex::display() {
	cout << real;
	if (imag >= 0) 
		cout << "+";
	cout << imag << "i" << endl;
}


/* 友元函数的定义
Complex operator+ (Complex &c1, Complex &c2) { 
	Complex c;
	c.real = c1.real + c2.real; 
	c.imag = c1.imag + c2.imag;
	return c;
}

Complex operator- (Complex &c1, Complex &c2) { 
	Complex c; 
	c.real = c1.real - c2.real; 
	c.imag = c1.imag - c2.imag; 
	return c;
} */

int main() {	
	Complex c1(6, 7), c2(7, 8);
	cout << "c1: ";
	c1.display();
	cout << "c2: ";
	c2.display();
	cout << "c1+c2: ";
	(c1 + c2).display();
	cout << "c1-c2: "; 
	(c1 - c2).display();

	getchar();
	return 0;
}

你可能感兴趣的:(【C++】运算符重载练习内容)