运算符重载的注意点:
1、不能重载的运算符(五个): ::(作用域) .*(成员指针运算符) .(对象访问成员运算符) ?:(三目运算符) sizeof
2、只能通过成员函数重载(四个): = 、[ ]、 ( ) 和 -> 操作符
3、当无法修改左操作数的类时,使用全局函数(友元函数)进行重载
4、类成员函数因为拿不到cout这个类的源码,无法重载<<、>>
5、++操作符通过一个int参数进行前置与后置的重载(后置带有int伪参数)
6、C++中不要重载&&和||操作符(C++的函数参数都会被求值,无法实现短路规则)
7、操作符重载遵循函数重载的规则
8、operator关键字是操作符重载的关键
9、friend关键字可以对函数或类开发访问权限
下面代码为重载+、&&,实现现类的相加相与:
#include <iostream>
using namespace std;
class Test
{
private:
int m_a;
public:
Test();
Test(int a);
Test &operator +(const Test &t); //通过成员函数重载+运算符,实现类相加
bool operator &&(const Test &t); //重载&&运算符,类相与
};
Test::Test()
{
m_a = 0;
}
Test::Test(int a)
{
m_a = a;
}
Test &Test::operator +(const Test &t) //成员函数隐含this指针指向当前变量
{
cout<<"overload +"<<endl;
m_a = m_a + t.m_a;
return *this;
}
bool Test::operator &&(const Test &t)
{
cout<<"overload &&"<<endl;
return m_a && t.m_a;
}
int main()
{
Test t1(0);
Test t2(2);
if(t1 && (t1 + t2))
{
}
return 0;
}