#include<iostream>class Complex {private: double real; double imag;public: Complex(double r=0.0, double i=0.0) { real = r; imag = i; } Complex operator+(Complex c2); Complex operator-(Complex c2); void display();};Complex Complex::operator+(Complex c2) { Complex c; c.real = real + c2.real; c.imag = imag + c2.imag; return c;}Complex Complex::operator-(Complex c2) { Complex c; c.real = real - c2.real; c.imag = imag - c2.imag; return c;}void Complex::display() { std::cout << "(" << real << "," << imag << ")" << std::endl;}int main() { Complex c1(4, 3), c2(2, 1), c3(0, 0); std::cout << "c1="; c1.display(); std::cout << "c2="; c2.display(); c3 = c1 - c2; std::cout << "c3="; c3.display(); c3 = c1 + c2; std::cout << "c3="; c3.display(); return 0;} 要求重载运算符函数为友元函数
时间: 2023-06-26 15:06:14 浏览: 117
#include<iostream>class Complex {private: double real; double imag;public: Complex(double r=0.0, double i=0.0) { real = r; imag = i; } friend Complex operator+(Complex c1, Complex c2); friend Complex operator-(Complex c1, Complex c2); void display();};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;}void Complex::display() { std::cout << "(" << real << "," << imag << ")" << std::endl;}int main() { Complex c1(4, 3), c2(2, 1), c3(0, 0); std::cout << "c1="; c1.display(); std::cout << "c2="; c2.display(); c3 = c1 - c2; std::cout << "c3="; c3.display(); c3 = c1 + c2; std::cout << "c3="; c3.display(); return 0;}
阅读全文