class Complex // & & Complex # {public: Complex){real=0;imag=0;? 1定义构造函数 Complex (double r,double i (real=r;imag=isy 1/ Complex complex add (Complex &c2);11声明 void displav0;11 声明输出函教 private: double real;11 实部 double imag; 11 虛部 }; { Complex Complex:: complex add(Complex &c2) Complex c; c.real=real+c2.real; c.imag=imag+c2.imag; return c; }这代码中c.real=real+c2.real;是什么意思
时间: 2024-02-26 22:55:09 浏览: 143
这行代码的意思是将当前对象的实部(real)与参数对象(c2)的实部(c2.real)相加,并将结果赋值给c对象的实部(c.real)。即计算出两个Complex对象实部之和,并将结果保存在一个新的Complex对象c中。同样的,这行代码对于虚部(imag)也做了类似的操作。最后将结果的Complex对象返回。
相关问题
用C++给下面的代码写运行部分。class COMPLEX {private: double real; double imag;public: COMPLEX(double r = 0, double i = 0) : real(r), imag(i) {} COMPLEX operator+(const COMPLEX& rhs) const { return COMPLEX(real + rhs.real, imag + rhs.imag); } COMPLEX operator-(const COMPLEX& rhs) const { return COMPLEX(real - rhs.real, imag - rhs.imag); } COMPLEX& operator=(const COMPLEX& rhs) { real = rhs.real; imag = rhs.imag; return *this; }};
以下是用C++编写的运行部分:
```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) {}
COMPLEX operator+(const COMPLEX& rhs) const {
return COMPLEX(real + rhs.real, imag + rhs.imag);
}
COMPLEX operator-(const COMPLEX& rhs) const {
return COMPLEX(real - rhs.real, imag - rhs.imag);
}
COMPLEX& operator=(const COMPLEX& rhs) {
real = rhs.real;
imag = rhs.imag;
return *this;
}
};
int main() {
COMPLEX a(1, 2), b(3, 4), c;
c = a + b;
cout << c.real << " + " << c.imag << "i" << endl;
c = a - b;
cout << c.real << " + " << c.imag << "i" << endl;
return 0;
}
```
在上述代码中,我们定义了一个名为`COMPLEX`的类,它表示一个复数,具有实部和虚部两个成员变量。我们使用构造函数初始化这两个成员变量,并且使用运算符重载函数`operator+`和`operator-`分别实现了复数的加法和减法。同时,我们也定义了一个赋值运算符`operator=`,用于将一个复数赋值给另一个复数。
在`main()`函数中,我们创建了两个复数对象`a`和`b`,并将它们相加和相减,将结果分别赋值给复数对象`c`。最后,我们输出了`c`的实部和虚部,以验证我们的代码是否正确。
将运算符+和-重载为 complex 类的友元函数。 #include<iostream.h> class complex { 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(); //显示复数的值 private: //私有成员 double real; double imag; }; 完成该类的实现并编译运行该程序。
以下是重载运算符+和-的实现:
```cpp
#include<iostream>
using namespace std;
class complex
{
public:
complex(double r = 0.0, double i = 0.0)
{
real = r;
imag = i;
}
void display()
{
cout << real << "+" << imag << "i" << endl;
}
friend complex operator+(complex c1, complex c2);
friend complex operator-(complex c1, complex c2);
private:
double real;
double imag;
};
complex operator+(complex c1, complex c2)
{
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
complex operator-(complex c1, complex c2)
{
return complex(c1.real - c2.real, c1.imag - c2.imag);
}
int main()
{
complex c1(1.0, 2.0), c2(2.0, 3.0);
complex c3 = c1 + c2;
complex c4 = c1 - c2;
c3.display(); // 输出 3+5i
c4.display(); // 输出 -1-1i
return 0;
}
```
运行结果:
```
3+5i
-1-1i
```
阅读全文