// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Complex
{
float a;
float b;
public:
Complex():a(),b(){}
Complex(const float& a, const float& b):a(a),b(b){}
Complex operator+(const Complex& com2)
{
return Complex((a+com2.a),(b+com2.b));
}
Complex operator-(const Complex& com2)
{
return Complex((a-com2.a),(b-com2.b));
}
Complex operator*(const Complex& com2)
{
return Complex((a*com2.a),(b*com2.b));
}
Complex operator/(const Complex& com2)
{
return Complex((a/com2.a),(b/com2.b));
}
/*成员函数前置--:*/
Complex& operator--()
{
--a;
--b;
return *this;
}
/*友元函数前置--:*/
//friend Complex& operator--(Complex& com)
//{
// --com.a;
// --com.b;
// return com;
//}
/*成员函数后置--:*/
/*Complex operator--(int)
{
Complex temp(*this);
a--;
b--;
return temp;
}*/
/*友元函数后置--:*/
friend Complex operator--(Complex& com,int)//(Complex& com,int)中不加& 就不能改变自己的值
{
Complex temp(com);
com.a--;
com.b--;
return temp;
}
Complex& operator=(const Complex& b)//必须是成员函数,与=相关的都必须是成员函数,还有[ ]和()
{
this->a=b.a;
this->b=b.b;
return *this;
}
friend ostream& operator<<(ostream&o,const Complex& com)//必须是友元函数
{
return o << com.a << " + " << com.b << "i";
}
friend istream& operator>>(istream& in,Complex& com)//必须是友元函数
{
return in >> com.a >> com.b ;//return in >> com.a >> " + " >> com.b >>"i"; 错误 没有这些符号的定义
}
//void show()
//{
// char * str;
// int dec, sign, ndigits = 3;
// str = _fcvt_s(a, ndigits, &dec, &sign);
// printf("Original number; %f\n" , a) ;
// printf ("Converted string; %s\n",str);
// printf ("Decimal place: %d\n" , dec) ;
// printf ("Sign: %d\n" , sign) ;
// //str = fcvt(b, ndigits, &dec, &sign);
//}
};
int _tmain(int argc, _TCHAR* argv[])
{
Complex a(1,5);
Complex b(5,6);
a=a+b;
cout << a << endl;
cout << --a << endl;
cout << a-- << endl;
cout << a << endl;
Complex c;
cout << "a:" << a << endl;
cout << "c:" << c << endl;
c=a--;
cout << "c:" << c << endl;
c=a;
cout << "c:" << c << endl;
cin >> c ;
cout << "c:" << c << endl;
c.show();
system("pause");
return 0;
}
写一个复数类Complex,(复数形如3.2+5.6i,2.9-1.3i,其中i*i=-1)。要求支持+-*/,++、--,到bool类型和string类型的转换,支持>>、<<运算符。
最新推荐文章于 2022-12-16 14:28:04 发布