C++不允许用户自己定义新的运算符,只能对已有的运算符进行重载.
运算符重载:
有5个运算符不允许重载:
1. . (成员访问运算符).
2. .* (成员指针访问运算符).
3. ::(域运算符).
4. sizeof(尺寸运算符).
5. ?: (条件运算符).
重载时需注意:
1. 不能改变运算符对象的操作个数.
2. 不能改变运算符的优先级别.
3. 不能改变运算符的结合性.
4. 重载运算符的函数不能有默认参数.
5. 重载运算符必须和用户定义的自定义类型的对象一起使用.其参数至少有一个是类对象或类对象的引用.(也就是说.参数不能全部是C++的标准类型.
这样约定是为了防止用户修改用于标准类型结构的运算符性质).
运算符重载格式:
函数类型 operator 运算符名称 (形参列表) {
对运算符的重载处理;
}
例子:
#include <iostream>
using namespace std;
class Complex {
public :
Complex();
Complex(int r, int i);
Complex operator+(Complex &d); //重载+法运算符.
void print();
private:
int i;
int r;
};
Complex::Complex() {
this->i = 0;
this->r = 0;
}
Complex::Complex(int i, int r) {
this->i = i;
this->r = r;
}
//重载+号.实现两数相加.
Complex Complex::operator+(Complex &d) {
Complex c;
c.i = this->i + d.i;
c.r = this->r + d.r;
return c;
}
void Complex::print(){
cout<<"("<<i<<","<<r<<")"<<endl;
}
void main(){
Complex c1(3,4), c2(5,6), c3;
c3 = c1 + c2; //这句话类似于:c3 = c1.operator+(c2);
cout<<"c1=";
c1.print();
cout<<"c2=";
c2.print();
cout<<"c3=";
c3.print();
}
简单例子:
#include <iostream>
using namespace std;
struct Complex
{
float real;
float image;
};
Complex operator + (Complex a, Complex b)
{
Complex c;
c.real = a.real + b.real;
c.image = a.image + b.image;
return c;
};
int main(int argc, char *argv[])
{
Complex aa = { 1, 2}, bb = { 2, 3};
Complex cc = operator+(aa, bb);
cout << cc.real << " " << cc.image << endl;
cout << "Run End!" << endl;
return 0;
}