顾名思义,重载便是重新赋予新的含义。
运算符重载的方法:定义一个重载运算符的函数,在需要执行被重载的运算符时,系统就自动调用该函数,即本质上是通过定义函数来实现的。
重载运算符的函数一般格式为: 函数类型 operator 运算符名称 (形参表列){对运算符的重载处理}
例如: Complex operator+ (Complex& c1,Complex& c2);
以下运算符不能重载:
. (成员访问运算符)
.* (成员指针访问运算符)
:: (域运算符)
sizeof (长度运算符)
?: (条件运算符)
注意:
1.重载不能改变运算符操作数的个数、优先级、结合性
2.重载的运算符必须与自定义类型的对象一起使用,其参数至少应有一个是类对象
3.用于类对象的运算符一般必须重载,运算符“=”和“&”不必用户重载
a. =可以用于每一个类对象,可以利用它在同类对象之间相互赋值
b. &可返回类对象在内存中的起始地址
4. 运算符重载函数可以是类的成员函数、类的友元函数、普通函数
一般将单目运算符重载为成员函数,将双目运算符重载为友元函数
运算符重载函数作为类友元函数
#includeusing namespace std; class Complex { public: Complex() { real = 0; img = 0; } Complex(double r, double i) { real = r; img = i; } friend Complex operator + (Complex& c1, Complex& c2); void display(); private: double real; double img; }; Complex operator+(Complex& c1, Complex& c2) { return Complex(c1.real + c2.real, c1.img + c2.img); } void Complex::display() { cout << "c3=" << real << "+" << img<<"i"; } int main() { Complex c1(3, 5), c2(2, 5), c3; c3 = c1 + c2; c3.display(); }
若运算符重载函数不是Complex类的友元函数,它就没有权利访问Complex类的私有成员。
运算符重载函数作为类的成员函数
#includeusing namespace std; class Time { public: Time() { minute = 0; sec = 0; } Time(int m, int s) { minute = m; sec = s; } Time operator++(); void display() { cout << minute << ":" << sec << endl; } private: int minute; int sec; }; Time Time::operator++() { if (++sec >= 60) { sec -= 60; minute += 1; } return *this; } int main() { Time time1(34,0); for (int i = 0; i < 61; i++) { ++time1; time1.display(); } std::cout << "Hello World!n"; }



