C++类怎么创建

C++类怎么创建求解:这两道题所要求的类定义应该怎么建立?(是将多项式每一项当一个类对象还是一整个多项式创建为一个类对象?)这道题怎么写比较省事呢?是否需要使用封闭类呢?

#include <iostream>
#include <cmath>
using namespace std;
class Complex{
private:
double Real,Image;
public:
Complex (double r=0.0,double i=0.0){Real=r;Image=i;}
Complex(Complex &com){
Real=com.Real;
Image=com.Image;
}
void Print(){
cout<<"Real="<<Real<<'\t'<<"Image="<<Image<<endl;
}
Complex operator+(Complex);
Complex operator+(double);
Complex operator=(Complex);
Complex operator+=(Complex);
double abs(void);
Complex operator*(Complex);
Complex operator/(Complex);
};
Complex Complex::operator +(Complex c){
Complex temp(Real+c.Real,Image+c.Image);
return temp;
}
Complex Complex:: operator+(double d){
return Complex(Real+d,Image);
}
Complex Complex::operator =(Complex c){
Complex temp;
temp.Real=c.Real;
temp.Image=c.Image;
Real=temp.Real;
Image=temp.Image;
return temp;
}
Complex Complex::operator+=(Complex c){
Complex temp;
temp.Real=Real+c.Real;
temp.Image=Image+c.Image;
Real=temp.Real;
Image=temp.Image;
return temp;
}
double Complex::abs(void){
return sqrt(Real*Real+Image*Image);
}
Complex Complex::operator*(Complex c){

return Complex(Real*c.Real -Image*c.Image,Real*c.Image+c.Real *Image);
}
Complex Complex::operator/(Complex c){
double d=c.Real*c.Real+c.Image*c.Image;
return Complex((Real*c.Real+Image*c.Image)/d,(Image*c.Image-Real*c.Real)/d);
}
int main(){
Complex c1(1.0,1.0),c2(2.0,2.0),c3(4.0,4.0),c;

c1.Print();
double d=0.5;
c=c2+c3;c.Print();
c+=c1;c.Print();
c=c+d;c.Print();
c=c2*c3;c.Print();
c=c3/c1;c.Print();
cout<<"c3的模为:"<<c3.abs()<<endl;
c=c3=c2=c1;c.Print();
c+=c2+=c1;c.Print();
return 0;

}

第二个版本:
#include <iostream.h>
class complex
{
public:
complex(){real=imag=0;} //默认构造函数
complex(double r,double i) //构造函数重载
{real=r;imag=i;}
complex operator+(const complex &c); //复数类+运算符重载
complex operator-(const complex &c); //复数类-运算符重载
friend void print(const complex &c); //打印复数方法
private:
double real,imag; //私有类成员,分别代表实数部分和虚数部分
};
inline complex complex :: operator+(const complex &c) //复数类+运算符重载实现
{return complex (real+c.real,imag+c.imag);}
inline complex complex :: operator-(const complex &c) //复数类-运算符重载实现
{return complex (real-c.real,imag-c.imag);};
void print(const complex &c) //打印复数方法实现
{
if(c.imag<0)
cout<<c.real<<c.imag<<'i';
else
cout<<c.real<<'+'<<c.imag<<'i';
}
void main()
{
complex c1(2.0,3.0),c2(4.0,-5.0),c3; //C1,C2由构造函数的参数决定了使用complex(double r,double i)这个构造函数,C3使用默认构造函数
c3=c1+c2; //这里的加法使用了重载了的+运算符
cout<<"\nc1+c2=";
print(c3);
c3=c1-c2; //这里的减法使用了重载了的-法运算符
cout<<"\nc1-c2=";
print(c3);
cout<<endl;
}追问

你说的是复数类的,不是多项式类的呀

我提高悬赏了

温馨提示:答案为网友推荐,仅供参考
相似回答