急。求帮忙。C++请给出复数类构造函数、加法、减法及输出运算符(+,-, <<)重载函数,以完成下面的程序。
要求加法运算符采用成员函数方式,减法运算符采用友元方式。#include<iostream.h>classComplex{doublereal,imag;public:…...
要求加法运算符采用成员函数方式,减法运算符采用友元方式。
#include<iostream.h>
class Complex
{
double real, imag;
public:
…
};
void main()
{
Complex c1(3.0,5.0),c2(-1.0,2.0), c3;
cout<<”c1=”<<c1<<endl;
cout<<”c2=”<<c2<<endl;
c3=c1+c2;
cout<<”c1+c2=”<<c3<<endl;
c3=c1-c2;
cout<<”c1-c2=”<<c3<<endl;
}
请 展开
#include<iostream.h>
class Complex
{
double real, imag;
public:
…
};
void main()
{
Complex c1(3.0,5.0),c2(-1.0,2.0), c3;
cout<<”c1=”<<c1<<endl;
cout<<”c2=”<<c2<<endl;
c3=c1+c2;
cout<<”c1+c2=”<<c3<<endl;
c3=c1-c2;
cout<<”c1-c2=”<<c3<<endl;
}
请 展开
2012-06-27
展开全部
#include <iostream.h>
class Complex
{
double real, imag;
public:
Complex( double r = 0.0, double i = 0.0 )
{
real = r;
imag = i;
}
Complex( const Complex & c )
{
real = c.real;
imag = c.imag;
}
Complex operator+( const Complex & c ) const
{
return Complex( real + c.real, imag + c.imag );
}
friend Complex operator-( const Complex & c1, const Complex & c2 )
{
return Complex( c1.real - c2.real, c1.imag - c2.imag );
}
Complex & operator=( const Complex & c )
{
if ( this == &c )
{
return *this;
}
real = c.real;
imag = c.imag;
return *this;
}
friend ostream & operator<<( ostream & os, const Complex & c )
{
os << c.real << ", " << c.imag;
return os;
}
};
void main()
{
Complex c1( 3.0, 5.0 ), c2( -1.0, 2.0 ), c3;
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
c3 = c1 - c2;
cout <<"c1 - c2 = " << c3 << endl;
}
class Complex
{
double real, imag;
public:
Complex( double r = 0.0, double i = 0.0 )
{
real = r;
imag = i;
}
Complex( const Complex & c )
{
real = c.real;
imag = c.imag;
}
Complex operator+( const Complex & c ) const
{
return Complex( real + c.real, imag + c.imag );
}
friend Complex operator-( const Complex & c1, const Complex & c2 )
{
return Complex( c1.real - c2.real, c1.imag - c2.imag );
}
Complex & operator=( const Complex & c )
{
if ( this == &c )
{
return *this;
}
real = c.real;
imag = c.imag;
return *this;
}
friend ostream & operator<<( ostream & os, const Complex & c )
{
os << c.real << ", " << c.imag;
return os;
}
};
void main()
{
Complex c1( 3.0, 5.0 ), c2( -1.0, 2.0 ), c3;
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
c3 = c1 - c2;
cout <<"c1 - c2 = " << c3 << endl;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询