1. 不能重载的运算符: “.” “:: ” “?:” “sizeof”
2. 前置++与后置++
// 前置++
Object& operator++(){
a++;
return *this;
}
// 后置++
Object operator++(int){
Object temp(*this);
this->a++;
return temp;
}
3. 重载->和*
class SmartPointer{
public:
SmartPointer(Person* person){
this->pPerson = person;
}
//重载指针的->、*操作符
Person* operator->(){
return pPerson;
}
Person& operator*(){
return *pPerson;
}
~SmartPointer(){
if (pPerson != NULL){
delete pPerson;
}
}
public:
Person* pPerson;
};
4. 赋值(=)运算符重载
//重载赋值运算符
Person& operator=(const Person& person){
this->mID = person.mID;
this->mAge = person.mAge;
return *this;
}
- 重载赋值运算符时,要考虑本对象在赋值之前是否有堆内存,不能简单替换指针
- Person person2 = person1; // 调用拷贝构造、
- person2 = person1; // 调用operator=函数
- 如果没有重载运算符,编译器会自动创建默认的赋值运算符重载函数,行为类似于拷贝默认构造,进行简单的值拷贝
5. 函数调用符号()重载
- 即为仿函数
6. 不要重载&&、||
- 原因:无法实现短路原则。短路原则即保证首先计算左边,如果能够决定结果,则无需计算右边,而且保证不需要
7. 总结:
- =、[]、()、->操作符只能通过成员函数进行重载
- <<和>>只能通过全局函数配合友元函数进行重载(cout << )
- 不要重载 && 和 || 操作符因为无法实现短路原则
- 常规建议