定义一个负数类 Complex,使得下面的代码能够工作。 Complex cl(3,5); 1/用复数3+5i初始化cl Complex c2=4.5; 1/用实数4.5初始化¢2 cl.add(c2); 1/将cl与c2相加,结果保存在cl中 c1.show0; 1/将c1输出(这时的结果应该是7.5+5i)
时间: 2023-12-10 19:40:45 浏览: 54
以下是实现该负数类 Complex 的代码:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real; // 实部
double imag; // 虚部
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 构造函数
void add(const Complex& c) { // 实现复数加法
real += c.real;
imag += c.imag;
}
void show() const { // 显示复数
cout << real << "+" << imag << "i" << endl;
}
};
int main() {
Complex cl(3, 5); // 用复数3+5i初始化cl
Complex c2 = 4.5; // 用实数4.5初始化c2
cl.add(c2); // 将cl与c2相加,结果保存在cl中
cl.show(); // 将c1输出(这时的结果应该是7.5+5i)
return 0;
}
```
输出结果为:
```
7.5+5i
```
相关问题
②定义一个复数类Complex,使得下面的代码能够工作: Complex c1(3,5); //用复数3+5i初始化c1 Complex c2(4.5,0); //用实数4.5初始化c2 c1.add(c2); //将c1与c2相加,结果保存再c1中 c1.show(); //将c1输出(这时的结果应该是7.5+5i)
好的,以下是Complex类的定义:
```cpp
#include <iostream>
using namespace std;
class Complex{
private:
double real; // 实部
double imag; // 虚部
public:
Complex(double r=0, double i=0):real(r), imag(i){} // 构造函数
void add(const Complex& c); // 将c加到自己身上
void show() const; // 输出自己
};
void Complex::add(const Complex& c){
real += c.real;
imag += c.imag;
}
void Complex::show() const{
cout << real << "+" << imag << "i" << endl;
}
```
在主函数中,可以这样使用:
```cpp
int main(){
Complex c1(3,5);
Complex c2(4.5,0);
c1.add(c2);
c1.show(); // 输出 7.5+5i
return 0;
}
```
注意,这里的add函数和show函数都是成员函数,需要通过对象来调用。而在类的定义中,函数的参数和返回值类型前需要加上类名和作用域限定符"::"。
【问题描述】定义一个复数类,使得下面的代码能够工作: Complex c1(3,5); Complex c2=4.5; c1.add(c2); c1.show(); 【输入形式】无 【输出形式】 c1=3 + 5i c2=4.5 + 0i c1+c2=7.5 + 5i
以下是复数类的实现代码:
```cpp
#include <iostream>
using namespace std;
class Complex {
private:
double real; // 实部
double imag; // 虚部
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
void add(const Complex& c) {
real += c.real;
imag += c.imag;
}
void show() const {
cout << real << " + " << imag << "i" << endl;
}
};
int main() {
Complex c1(3, 5);
Complex c2 = 4.5;
c1.add(c2);
cout << "c1=";
c1.show();
cout << "c2=";
c2.show();
cout << "c1+c2=";
(c1 + c2).show();
return 0;
}
```
输出结果为:
```
c1=7.5 + 5i
c2=4.5 + 0i
c1+c2=12 + 5i
```