#include <iostream>
using namespace std;
class CComplex
{
public:
CComplex(int r = 0, int i = 0) :
mreal(r), mimage(i) {}
CComplex operator+(const CComplex &src)
{
/*CComplex comp;
comp.mreal = this->mreal + src.mreal;
comp.mimage = this->mimage + src.mimage;
return comp;*/
return CComplex(this->mreal + src.mreal, this->mimage + src.mimage);
}
CComplex& operator++()
{
mreal++;
mimage++;
return *this;
}
CComplex operator++(int)
{
CComplex comp = *this;
mreal++;
mimage++;
return comp;
}
void operator+=(const CComplex &src)
{
mreal += src.mreal;
mimage += src.mimage;
}
void show()
{
cout << "mreal:" << mreal <<" "<< "mimage" << mimage << endl;
}
private:
int mreal; //复数的实部
int mimage; //复数的虚部
friend CComplex operator+(const CComplex &a, const CComplex &b);
friend ostream& operator<<(ostream &out, const CComplex &src);
friend istream& operator >> (istream &in, CComplex &src);
};
CComplex operator+(const CComplex &a, const CComplex &b)
{
return CComplex(a.mreal + b.mreal, a.mimage + b.mimage);
}
ostream& operator<<(ostream &out, const CComplex &src)
{
out << "mreal:" << src.mreal << "mimage" << src.mimage << endl;
return out;
}
istream& operator >> (istream &in, CComplex &src)
{
in >> src.mreal >> src.mimage;
return in;
}
int main()
{
CComplex comp1(10, 10);//定义实部和虚部都是10的复数comp1
CComplex comp2(20, 20);//定义实部和虚部都是20的复数comp2
CComplex comp3 = comp1 + comp2;
comp3.show();
/*显然编译器不知道两个复数类的对象如何相加,它会去CComplex类中找comp1的“+”方法,而把comp2当做实参
因此需要些加法运算符的重载函数 comp1.operator+(comp2)*/
CComplex comp4 = comp1 + 20;
//comp4.operator+(20) 20从int -> CComplex 生成临时对象CComplex(20)
comp4.show();
//编译器做对象运算的时候,会调用对象的运算符重载函数(优先调用成员方法),如果没有成员方法,
//就在全局作用域找合适的运算符重载函数
CComplex comp5 = 20 + comp1;
comp5.show();
comp5 = comp1++;//单目运算符 不带参数 前置 带一个整形参数 后置
comp5.show();
comp1.show();
comp5 = ++comp1;
comp5.show();
comp1.show();
comp1 += comp2;
//comp1.show();//对象的输出
cout << comp1 << endl;
cin >> comp1 >> comp2;
cout << comp1 << comp2;
return 0;
}
C++|运算符重载
最新推荐文章于 2025-03-05 21:19:24 发布