
2个回答
展开全部
C++实现的复数类,代码如下
//complex.cpp
#include <iostream>
using namespace std;
class complex{
//复数类
public:
complex(double r=0.0, double i=0.0);
complex operator+(const complex& p)const;//重载运算符+
friend ostream& operator <<(ostream& out,const complex& pp);//重载操作符<<
private:
double real,imag;
};
complex::complex(double r,double i){
real = r; imag = i;
}
complex complex::operator +(const complex& p)const{
return complex(real + p.real,imag + p.imag);
}
ostream& operator <<(ostream& out,const complex& pp){
out<<pp.real<<"+"<<pp.imag<<"i";
return out;
}
void main(){
int a = 2, b = 6,integer;
double e = 2.4, f = 7.5, real;
complex c1(4,2),c2(3,3.7),c;
integer = a + b;
cout<<integer<<endl;
real = e + f;
cout<<real<<endl;
c = c1 + c2;
cout<<c<<endl;
}
Output:
8
9.9
7+5.7i
//complex.cpp
#include <iostream>
using namespace std;
class complex{
//复数类
public:
complex(double r=0.0, double i=0.0);
complex operator+(const complex& p)const;//重载运算符+
friend ostream& operator <<(ostream& out,const complex& pp);//重载操作符<<
private:
double real,imag;
};
complex::complex(double r,double i){
real = r; imag = i;
}
complex complex::operator +(const complex& p)const{
return complex(real + p.real,imag + p.imag);
}
ostream& operator <<(ostream& out,const complex& pp){
out<<pp.real<<"+"<<pp.imag<<"i";
return out;
}
void main(){
int a = 2, b = 6,integer;
double e = 2.4, f = 7.5, real;
complex c1(4,2),c2(3,3.7),c;
integer = a + b;
cout<<integer<<endl;
real = e + f;
cout<<real<<endl;
c = c1 + c2;
cout<<c<<endl;
}
Output:
8
9.9
7+5.7i
展开全部
class complex
{
public:
complex(double r=0.0, double i=0.0):real(r), imag(i){}
void Output(){cout << real << " + " << imag << "i" << endl;}
private:
double real;
double imag;
};
void main()
{
complex a(2,3);
a.Output();
}
{
public:
complex(double r=0.0, double i=0.0):real(r), imag(i){}
void Output(){cout << real << " + " << imag << "i" << endl;}
private:
double real;
double imag;
};
void main()
{
complex a(2,3);
a.Output();
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询