封装一个复数类CPLX,用来处理复数功能和运算,支持以下操作: 1. CPLX::CPLX()构造:初始化一个实部、虚部均为0的复数,产生一行以“CREATE()”开始的输出,并输出复数的实部和虚部; 2. CPLX::~CPLX()析构:产生一行以“RELEASE()”开始的输出,并输出复数的实部和虚部; 3. CPLX::real():返回实部; CPLX::imag():返回虚部。 4. CPLX::real(double):传参修改实部; CPLX::imag(double):传参修改虚部; ----------------------------------------------------------------------------- 你设计一个CPLX类,使得main()函数能够运行并得到正确的输出。调用格式见append.ccint main() { int cases; cin >> cases; for(int i = 1; i <= cases; ++i) { double a, b; cin >> a >> b; cout << "=========================" << endl; CPLX cplx; cplx.real(a); cplx.imag(b); cout << "Complex real part is " << cplx.real() <<", imaginary part is " << cplx.imag() << "." << endl; } cout << "=========================" << endl; }
时间: 2023-06-12 13:04:35 浏览: 450
使用普通计算器进行复数运算.pdf
以下是CPLX类的实现:
```c++
#include <iostream>
using namespace std;
class CPLX {
private:
double real_part;
double imag_part;
public:
CPLX() : real_part(0), imag_part(0) {
cout << "CREATE()" << endl;
cout << "Complex real part is " << real_part << ", imaginary part is " << imag_part << "." << endl;
}
CPLX(double real, double imag) : real_part(real), imag_part(imag) {
cout << "CREATE()" << endl;
cout << "Complex real part is " << real_part << ", imaginary part is " << imag_part << "." << endl;
}
~CPLX() {
cout << "RELEASE()" << endl;
cout << "Complex real part is " << real_part << ", imaginary part is " << imag_part << "." << endl;
}
double real() const {
return real_part;
}
double imag() const {
return imag_part;
}
void real(double real) {
real_part = real;
}
void imag(double imag) {
imag_part = imag;
}
};
```
其中,CPLX类有两个私有变量:实部和虚部。构造函数有两种,一种是默认构造函数,实部和虚部都为0;另一种是带参数的构造函数,可以传入实部和虚部的值。析构函数会输出释放的信息和当前实部和虚部的值。real()和imag()函数分别返回实部和虚部的值,而real(double)和imag(double)函数则可以传入参数修改实部和虚部的值。
可以按照以下调用方式测试CPLX类:
```c++
int main() {
int cases;
cin >> cases;
for(int i = 1; i <= cases; i++) {
double a, b;
cin >> a >> b;
cout << "=========================" << endl;
CPLX cplx;
cplx.real(a);
cplx.imag(b);
cout << "Complex real part is " << cplx.real() <<", imaginary part is " << cplx.imag() << "." << endl;
}
cout << "=========================" << endl;
return 0;
}
```
阅读全文