赞
踩
关键字operator加上运算符名的函数称为运算符函数
operator+(8,9) //A
operator+(8.1,9.1) //B
int operator+(int,int) //A1
double operator+(double,double) //B1
根据函数重载规则,(A)调用A1, (B)调用B1
这样函数重载机制实现了运算符重载,运算符重载实际是函数重载
. | 成员选择运算符 |
---|---|
.* | 成员指针运算符 |
:: | 作用域分辨符 |
?: | 三目选择运算符 |
sizeof | 计算数据大小运算符 |
重载后运算符的优先级与结合性不会改变 |
---|
不能改变原运算符操作的个数 |
不能重载C++没有的运算符 |
不能改变运算符的原有意义 |
不能重载非静态成员(全局成员) |
格式:
举例:
class Day { public : Day(int year = 1900, int month = 1, int day = 1) { _year = year; _month = month; _day = day; } Day (const Day& d) { _year = d._year; _month = d._month; _day = d._day; } Day& operator=(const Day& d)//在赋值运算符中运用引用就可以提高效率 { if(this != &d) { _year = d._year; _month = d._month; _day = d._day; } return *this; //return Day(_year,_month,_day) 函数返回 } private: int _year ; int _month ; int _day ; };
使用了this指针返回对象,和函数返回的区别:
函数返回对象时需要调用构造函数建立临时对象
this指针返回对象不需要 调用构造函数,但会调用拷贝构造函数。
const修饰的成员函数,称之为const成员函数
class Day { public: void Display()const //void Display(const Day* this)修饰后 { //cout<<*this->_year; cout<<_year; } private: int _year; }; int main() { Day d1; d. return 0; }
调用时要注意,权限只能缩小或者平移,不能放大
class Day { public: void Display() //没有const修饰 { cout << _year; } private: int _year=1; }; int main() { const Day d1;//报错 d1.Display(); return 0; }
函数不加const就无法被const对象调用
class Day
{
public :
Day* operator&()
{
return this ;
}
const Day* operator&()const
{
return this ;
}
private :
int _year ;
};
这两个运算符一般不需要重载,使用编译器生成的默认取地址的重载即可。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。