将加减运算符重载为复数类成员函数
规则:实部虚部分别相加减。操作数:两个操作数都是复数类的对象
#include<iostream>
using namespace std;
class complex {
public:
complex(double r = 0.0, double i = 0.0) :real(r),image(i)
{}
complex operator + (const complex& rc2) const;
complex operator - (const complex& rc2) const;
void display();
double real, image;
};
complex complex::operator + (const complex& rc2) const
{
return complex(real + rc2.real, image + rc2.image);
}
complex complex::operator - (const complex& rc2) const
{
return complex(real - rc2.real, image - rc2.image);
}
void complex::display()
{
cout << "(" << real << "," << image << ")" << endl;
}
int main()
{
complex c1(2, 4), c2(1, 3), c3,c4;
cout <<"c1=" <<"(" << c1.real << "," << c1.image << ")" << endl;
cout << "c2=" << "(" << c2.real << "," << c2.image << ")" << endl;
c3 = c1 + c2;
c4 = c1 - c2;
cout << "c3 = c1 + c2";
c3.display();
cout << "c4 = c1 - c2";
c4.display();
}
期末之九运算符重载
最新推荐文章于 2025-05-29 23:36:29 发布