"运算符"几乎是所有的编程语言中都会出现的概念,例如+、-、*、/ 就是最常见的运算符。C++预定义的运算符只能作用于C++已经定义的基本数据类型,对于用户自定义的类型,如果也需要进行类似的运算操作的话,就需要重新去定义这些运算,赋予运算符新的功能,即"运算符重载"。
一、运算符重载时需要注意的点
二、运算符重载的语法:
<返回值类型> operator<运算符>(<形参列表>)
{
//函数体
}
三、运算符重载实例(复数类)
#include <IOStream>
using namespace std;
class Complex
{
public:
Complex(int real, int imag);
~Complex();
// 成员函数重载运算符
Complex& operator+(const Complex& c);
// 友元函数重载"流操作运算运算符"
friend ostream& operator<<(ostream& out, const Complex& c);
private:
int real_;
int imag_;
};
Complex::Complex(int real, int imag)
{
real_ = real;
imag_ = imag;
}
Complex::~Complex()
{
}
Complex& Complex::operator+(const Complex& c)
{
this->real_ += c.real_;
this->imag_ += c.imag_;
return *this;
}
ostream& operator<<(ostream& out, const Complex& c)
{
out << c.real_;
if(c.imag_ > 0)
out << "+" << c.imag_ << "i";
else
out << c.imag_ << "i";
return out;
}
int main()
{
Complex a(4, -6);
cout << a << endl; // 等于operator<<(cout, a);
Complex b(4, 3);
cout << b << endl;
Complex c = a + b;
cout << c << endl;
return 0;
}