#include
using namespace std;
class CComplexNumber
{
public:
CComplexNumber(int shi=0, int xu=0):shibu(shi),xubu(xu) {} //为构造函数添加默认值就好了
friend ostream& operator << (ostream& cout , const CComplexNumber& rhs);
//friend istream& operator>>(istream& cin,CComplexNumber& rhs);
CComplexNumber operator * (CComplexNumber& rhs)
{
int a = shibu * rhs.shibu - xubu * rhs.xubu;
int b = shibu * rhs.xubu + xubu * rhs.shibu;
return CComplexNumber(a,b); }
int operator = (CComplexNumber& rhs)
{
return rhs.shibu;
}
CComplexNumber& operator = (int rhs)
{
shibu = rhs;
xubu = 0;
return *this;
}
operator int() //定义一个CComplexNumber到int的转换
{
return shibu;
}
~CComplexNumber() {} // 原先没写
private:
int shibu;
int xubu;
};
ostream& operator << (ostream& cout , const CComplexNumber& rhs)
{
if (rhs.xubu > 0)
{
cout << rhs.shibu << "+" << rhs.xubu << "i" << endl;
}
if (rhs.xubu == 0)
{
cout << rhs.shibu << endl;
}
if (rhs.xubu < 0)
{
cout << rhs.shibu << rhs.xubu << "i" << endl;
}
return cout;
}
int main(void)
{
CComplexNumber CComplexNumber1(2,-3);
CComplexNumber CComplexNumber2(4,5);
CComplexNumber CComplexNumber3 = 6; //调用构造函数
CComplexNumber CComplexNumber4 = CComplexNumber1 * CComplexNumber2;
int i = CComplexNumber1; // 调用operator int()
cout << "CComplexNumber1 is :" << CComplexNumber1 << endl;
cout << "CComplexNumber2 is :" << CComplexNumber2 << endl;
cout << "CComplexNumber3 is :" << CComplexNumber3 << endl;
cout << "CComplexNumber4 is :" << CComplexNumber4 << endl;
cout << "i is:" << i << endl;
return 0;}