【发布时间】:2020-05-10 03:51:48
【问题描述】:
#include<iostream>
#include<cmath>
using namespace std;
class Complex
{
private:
double real;
double imag;
double modulus;
public:
Complex(){
cout<<"Default constructor is called"<<endl;
}
Complex (double realIn, double imagIn){
this->real = realIn;
this->imag = imagIn;
}
Complex (const Complex &a ){
real = a.real;
imag = a.imag;
modulus = a.modulus;
}
double getModulus(){
return modulus = sqrt(real * real + imag * imag);
}
void display(){
cout<<real<<" + "<<imag<<" i"<<endl;
}
bool operator > (const Complex &c1){
return modulus > c1.modulus? true : false;
}
Complex& operator = (const Complex &c1){
real = c1.real;
imag = c1.imag;
modulus = c1.modulus;
}
};
int main(){
int num, i,j;
double real, imag;
cout<<" Input number of complex numbers: ";
cin>>num;
Complex* c[num];
for (i = 0; i < num; i++){
cout<<"Imput the real part of the complex number no."<<i+1<<endl;
cin>>real;
cout<<"Input the imagine part of the complex number no."<<i+1<<endl;
cin>>imag;
c[i] = new Complex(real, imag);
c[i]->display();
}
for (i = 0; i < num; i++){
for (j = i +1; j < num; i++){
if (c[j]->getModulus() > c[i]->getModulus() ? true:false){
if (true){
Complex* temp = c[j];
c[j] = c[i];
c[i] = temp;
}
}
}
}
system("CLS");
cout<<"The decreasing order of the complex numbers is: "<<endl;
for (i = 0; i < num; i++){
cout<<i+1<<" : ";
c[i]->display();
}
return 0;
}
我刚开始学习 OOP,尤其是重载函数。我被要求阅读复数列表并按降序打印(使用它们的模数进行比较)。但是,在我输入所有复数后它会停止。没有错误,所以我不知道我哪里弄错了。请帮我。非常感谢!
【问题讨论】:
标签: c++ oop operator-overloading