-->
当前位置:首页 > Eng > 正文内容

函数题:运算符重载(复数类Complex)

Luz2年前 (2022-11-19)Eng481
本题要求定义一个复数类Complex,类的声明见给出的代码,请给出类的完整实现,并通过测试程序。类的声明包括如下内容:
1. 数据成员,复数类的实部u和虚部v;
2. 对复数类实部和虚部的访问函数;
3. 构造函数;
4. 加号、减号运算符重载(遵守复数的运算规则);
5. 输入、输出运算符重载。

### 类的声明:
c++
class Complex{
private:
double u;
double v;
public:
Complex(double _u=0,double _v=0);
Complex operator+(const Complex&b);
Complex operator-(const Complex&b);
double getU() const;
double getV() const;
friend ostream&operator<<(ostream&os,const Complex&c);
friend istream&operator>>(istream&is,Complex&c);
};



### 测试程序:
c++
class Complex{
private:
double u;
double v;
public:
Complex(double _u=0,double _v=0);
double getU() const;
double getV() const;
Complex operator+(const Complex&b);
Complex operator-(const Complex&b);
friend ostream&operator<<(ostream&os,const Complex&c);
friend istream&operator>>(istream&is,Complex&c);
};
double Complex::getU() const
{
return u;
}
double Complex::getV() const
{
return v;
}
/* 请在这里填写答案 */

int main(){
Complex a;
cin>>a;
cout<<"复数a为:"<<a<<endl;
Complex b(3,4);
Complex c=a+b;
cout<<"复数c为:"<<c<<endl;
Complex d=a-b;
cout<<"复数d为:"<<d<<endl;
return 0;
}

### 测试程序的输入:

in
10 5


### 测试程序的输出:

out
复数a为:u=10,v=5
复数c为:u=13,v=9
复数d为:u=7,v=1


### 提示
下列代码为类实现的骨架代码
c++
Complex::Complex(double _u,double _v){
//代码
}
Complex Complex::operator+(const Complex&b){
//代码
}
Complex Complex::operator-(const Complex&b){
//代码
}
ostream&operator<<(ostream&os,const Complex&c){
//代码
}
istream&operator>>(istream&is,Complex&c){
//代码
}






answer:若无答案欢迎评论

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。