下述程序从控制台读取一个复数b的实部和虚部,然后将这个复数与复数a及实数3.2相加,得到复数c并输出。请参考注释将程序补充完整。#include<iostream> using namespace std; class Complex { double dReal; double dImage; public: //构造函数 ▁▁▁ //operator+操作符函数 ▁▁▁ //友元函数声明以帮助operator<<()函数访问Complex类的私有成员 ▁▁▁ }; ostream& operator<<(ostream& o, const Complex& c){ o << fixed << setprecision(1) << c.dReal << " + " << c.dImage << "i"; return o; } int main() { double dReal, dImage; cin >> dReal >> dImage; Complex a(1,1); Complex b(dReal,dImage); Complex c = a + b + 3.2; cout << c << endl; return 0; }
时间: 2024-03-31 07:33:28 浏览: 86
这是1.定义一个复数类 complex ,它的内部具有两个实例变量:realPart和imagPart,分别代表复数的实部和虚
5星 · 资源好评率100%
#include<iostream>
#include<iomanip>
using namespace std;
class Complex {
private:
double dReal;
double dImage;
public:
Complex(double dR = 0, double dI = 0) : dReal(dR), dImage(dI) {} //构造函数
Complex operator+(const Complex& c) const { //operator+操作符函数
return Complex(dReal + c.dReal, dImage + c.dImage);
}
friend Complex operator+(const Complex& c, double d); //友元函数声明以帮助operator<<()函数访问Complex类的私有成员
friend ostream& operator<<(ostream& o, const Complex& c);
};
Complex operator+(const Complex& c, double d) { //友元函数定义
return Complex(c.dReal + d, c.dImage);
}
ostream& operator<<(ostream& o, const Complex& c) { //operator<<操作符函数
o << fixed << setprecision(1) << c.dReal << " + " << c.dImage << "i";
return o;
}
int main() {
double dReal, dImage;
cin >> dReal >> dImage;
Complex a(1, 1);
Complex b(dReal, dImage);
Complex c = a + b + 3.2;
cout << c << endl;
return 0;
}
阅读全文