本关任务:已知复数类Complex的定义如下: class Complex { private: double real; double imag; public: Complex(); void Print(); friend bool Equal(Complex, Complex); };
任务要求
(1)实现构造函数,从键盘输入复数的实部和虚部;(2)完成友元函数Equal判断两个复数是否相等;(3)完成成员函数Print,输出复数;(4)设计main(),定义对象,调用友元函数Equal,输出相等或不相等的信息。
参考一下:
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex() {
cout << "请输入复数的实部和虚部:" << endl;
cin >> real >> imag;
}
void Print() {
cout << "复数为:" << real << " + " << imag << "i" << endl;
}
friend bool Equal(Complex c1, Complex c2) {
if (c1.real == c2.real && c1.imag == c2.imag) {
return true;
} else {
return false;
}
}
};
int main() {
Complex c1, c2;
c1.Print();
c2.Print();
if (Equal(c1, c2)) {
cout << "两个复数相等" << endl;
} else {
cout << "两个复数不相等" << endl;
}
return 0;
}