首先重载加减运算符
class plural
{
public:
plural(float real = 0.0, float vir = 0.0) :real(real), vir(vir) { cout << "有参构造" << endl; }
plural(const plural& p) :real(p.real), vir(p.vir) { cout << "拷贝构造" << endl; }
plural operator+(const plural& p) const
{
return plural(real + p.real, vir + p.vir);
}
plural operator-(const plural& p) const
{
return plural(real - p.real, vir - p.vir);
}
private:
float real; // 实部
float vir; // 虚部
};
重载分为两种:
(1)重载为类成员函数,这种情况下重载函数的第一个参数是隐式的this指针,就比如上面的operator+,参数是两个plural类对象,但是只需要传一个参数。此时我们调用时可以有一下两种写法,因为函数返回一个临时对象,我们用p3和p4去接收
int main()
{
plural p1(10,20);
cout << p1 << endl;
plural p2(10);
cout << p2 << endl;
plural p3(p1.operator+ (p2));
cout << p3 << endl;
plural p4 = p1 - p2;
cout << p4 << endl;
}
第一种写法就是传统的调用函数并传参的写法:plural p3(p1.operator+ (p2));
第二种就是重载后的简单写法:plural p4 = p1 - p2;
如果想要直接通过cout输出plural类对象,我们还得重载<<运算符,如果我们重载为类成员函数,那么代码如下:
ostream& operator<<(ostream& os)
{
if (this->vir == 0)
{
os << this->real;
}
else
{
os << this->real << "+" << this->vir << "i";
}
return os;
}
这个函数有两个参数,第一个是隐式的this指针,第二个是输出流对象os,插入运算符(operator<<)是有先后顺序的,也就是说,这样写的会导致实际运算是这样的: "类对象 << cout" , 所有我们不能像常规输出一样:
"cout << 类对象" , 我们必须显示调用重载函数,如下:
p4.operator<<(cout) << endl;
亦或是:
p4 << cout << endl;
这种形式才能打印到屏幕,这很明显不符合我们的预期,那种就只能使用另一种重载方式
(2)重载为类的友元函数
friend ostream& operator<<(ostream& os, const plural& p)
{
if (p.vir == 0)
{
os << p.real;
}
else
{
os << p.real << "+" << p.vir << "i";
}
return os;
}
这两个参数的顺序依然不能调换,不然调用的时候也得调换 . 因为类成员为私有属性,这个函数需要写为类的友元函数,如果写在类外需要去掉friend,同时在类内使用friend进行友元声明,这时候就可以直接通过cout对类对象进行输出了