#include <iostream> using namespace std; /*********在begin和end之间填入代码,实现complex类的定义,重载前置++运算符和重载后置++运算符及display()函数********/ /***********begin*************/ void Complex::display() { if(real==0) { if(imag>0) cout<<imag<<"i"; else if(imag==0) cout<<real; else cout<<imag<<"i"; } else { if(imag>0) cout<<real<<"+"<<imag<<"i"; else if(imag==0) cout<<real; else cout<<real<<imag<<"i"; } } /***********end************/ int main() { Complex c1,c2; cin>>c1.real>>c1.imag; c1.display(); cout<<endl; ++c1; c2=c1++; c2.display(); cout<<endl; c1.display(); }
时间: 2023-07-19 17:46:27 浏览: 130
#include_iostream.h_
4星 · 用户满意度95%
下面是完整的代码,实现了complex类的定义,重载了前置++运算符、后置++运算符和display()函数:
```
#include <iostream>
using namespace std;
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator++() {
++real;
++imag;
return *this;
}
Complex operator++(int) {
Complex temp = *this;
++real;
++imag;
return temp;
}
void display();
};
void Complex::display() {
if(real==0) {
if(imag>0)
cout<<imag<<"i";
else if(imag==0)
cout<<real;
else
cout<<imag<<"i";
} else {
if(imag>0)
cout<<real<<"+"<<imag<<"i";
else if(imag==0)
cout<<real;
else
cout<<real<<imag<<"i";
}
}
int main() {
Complex c1,c2;
cin>>c1.real>>c1.imag;
c1.display();
cout<<endl;
++c1;
c2=c1++;
c2.display();
cout<<endl;
c1.display();
return 0;
}
```
这段代码中,Complex类定义了两个私有成员变量real和imag来存储复数的实部和虚部,重载了前置++运算符和后置++运算符以实现复数的自增运算,同时还定义了display()函数来输出复数。在main函数中,输入了一个复数c1,并对其进行了前置自增运算和后置自增运算,并输出了相应的结果。
阅读全文