我在一开始学习C++编程时,对“运算符重载”这里一直很迷惑。例如对于输出运算符的重载,我刚开始是这样想的:C++明明提供了<<来进行输出,为什么还要重载一个呢?最后我通过查资料,结合我的理解,通俗地说:重载可以理解为“自己重写写”,因为C++提供的某些运算符并不能完全满足我们日常的编程需求,所以就要程序员自己写函数来实现某些运算符的要求。 例如,对于复数 1+2i,C++自带的输出<<是无法正确操作的,因为这个复数是自定义类型(没有形如a+bi的数据类型)。要是有表述不清楚的,请读者指正。以下就是我基于复数的一些操作进行的运算符重载的测试,测试环境为VS2013
#include <iostream>
#include <stdlib.h>
using namespace std;
class Complex
{
private:
double _real;
double _img;
friend ostream& operator<<(ostream& _cout, const Complex& c);
friend istream& operator>>(istream& _cin, Complex& c);
public:
//构造函数
Complex(double real = 0, double img = 0)
{
//cout << "构造函数~" << endl;
_real = real;
_img = img;
}
//拷贝构造函数
Complex(Complex& c)
{
//cout << "拷贝构造函数~" << endl;
_real = c._real;
_img = c._img;
}
//析构函数
~Complex()
{}
//赋值运算符重载
Complex& operator=(Complex& c)
{
if(this != &c)
{
_real = c._real;
_img = c._img;
return *this;
}
}
//+=重载
Complex& operator+=(Complex& c)
{
_real += c._real;
_img += c._img;
return *this;
}
//-=重载
Complex& operator-=(Complex& c)
{
_real -= c._real;
_img -= c._img;
return *this;
}
};
//输入运算符重载
istream& operator>>(istream& _cin, Complex& c)
{
cout << "请输入实部:";
_cin >> c._real;
cout << "请输入虚部:";
_cin >> c._img;
return _cin;
}
//输出运算符重载
ostream& operator<<(ostream& _cout, const Complex&c)
{
if (c._img > 0)
{
_cout << c._real << "+" << c._img << "i" << endl;
return _cout;
}
else if (c._img == 0)
{
_cout << c._real << endl;
return _cout;
}
else
{
_cout << c._real << c._img << "i" << endl;
return _cout;
}
}
void Test()
{
//调用构造函数
Complex com1(4.0, 3.0);
cout <<"com1:"<< com1 << endl;
//调用拷贝构造函数
Complex com2(com1);
//输出运算符重载
cout << "com2:" << com2 << endl;
Complex com3;
//测试输入运算符重载
cin >> com3;
cout << "com3:" << com3;
Complex com4;
//测试赋值运算符重载
com4 = com3; //亦可以进行连续赋值,com4 = com3 = com1,则com4为 1+2i;
cout << "com4:" << com4;
Complex com5(1.0, 2.0);
//测试+=运算符重载
com5 += com1;
cout << "com5:" << com5;
Complex com6(2.0, 1.0);
com6 -= com1;
cout << "com6:" << com6;
}
int main()
{
Test();
system("pause");
return 0;
}