C++ primer plus第六版课后编程题答案11.7


complex0.cpp

#include <iostream>
using namespace std;
//为了方便,声明和实现都写在这里
class complex0{
private:
	double shi;
	double xu;
public:
	complex0(){
		shi=xu=0;
	}
	complex0(double s,double x)
	{
		shi=s;
		xu=x;
	}
	~complex0(){};
	complex0 operator+(const complex0 &c)const
	{
		
		double ss=shi+c.shi;
		double xx=xu+c.xu;
		//complex0 t(ss,xx);
		//cout<<"test="<<t<<endl;
		return complex0(ss,xx);
	}
	complex0 operator-(const complex0 &c)const
	{
		double ss=shi-c.shi;
		double xx=xu-c.xu;
		return complex0(ss,xx);
	}
	complex0 operator*(const complex0 &c)
	{
		double ss=shi*c.shi-xu*c.xu;
		double xx=shi*c.shi+xu*c.xu;
		return complex0(ss,xx);
	}
	complex0 operator*(double s)const
	{
		double ss=shi*s;
		double xx=xu*s;
		return complex0(ss,xx);
	}
	complex0 operator~()
	{
		return complex0(-shi,-xu);
	}
	//友元函数重载*
	friend complex0 operator*(double s,const complex0 &c)
	{
		return c*s;
	}
	friend istream& operator>>(istream &os,complex0 &c)//不要用const,因为要改变其值
	{
		cout<<"please enter the shi:"<<endl;
		double ss;
		os>>ss;
		cout<<"please enter the xu:"<<endl;
		double xx;
		os>>xx;
		c.shi=ss;
		c.xu=xx;
		return os;	
	}
	friend ostream& operator<<(ostream &os,const complex0 &c)
	{
		os<<"("<<c.shi<<","<<c.xu<<"i)";
		return os;
	}
};

main117.cpp

#include <iostream>
#include "complex0.cpp"
using namespace std;
void main117()
{
	complex0 a(3.0,4.0);
	complex0 c;
	cout<<"Enter a complex number (q to quit):\n";
	while(cin>>c)
	{
	cout<<"c is "<<c<<endl;
	cout<<"complex conjugate is "<<~c<<endl;
	cout<<"a is "<<a<<endl;
	//complex0 ss=a+c;
	//cout<<"a+c is 11  "<<ss<<endl;
	cout<<"a+c is "<<a+c<<endl;
	cout<<"a-c is "<<a-c<<endl;
	cout<<"a*c is "<<a*c<<endl;
	cout<<"2*c is "<<2*c<<endl;
	cout<<"Enter a complex number (q to quit):\n";
	}

	cout<<"Done!\n";
	cin.get();
	cin.get();


}

 

 


发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注