重载运算符不需要一定是成员函数,以Person和<运算符为例,下列三种写法都是正确的
// "a//作为成员函数重载(常见)
class Person{
string name;
int age;
public:
Person(const char* name, int age):name(name),age(age){}
bool operator<(const Person& b);
};
bool Person::operator<(const Person& b)
{
//作为成员函数时,*this即为左操作数a
...
}
//作为友元函数重载
class Person{
string name;
int age;
public:
Person(const char* name, int age):name(name),age(age){}
friend bool operator<(const Person& a,const Person& b);
};
bool operator<(const Person& a,const Person& b)
{
...
}
//作为普通函数重载(不推荐)
class Person{
public://注意,重载运算符为普通函数时,使用到的类成员必须为public
string name;
int age;
public:
Person(const char* name, int age):name(name),age(age){}
};
bool operator<(const Person& a,const Person& b)
{
...
}
你可以不那样写,可以把它当作成员函数,加friend后只是为了说明了以下几点:
该函数是外部的一个函数,非类的成员函数
该函数内部使用该类的对象时可以访问该类的私有和保护成员
如果你把重载函数写成成员函数,而且是public属性,对于使用该操作符时其实没有差别,但是如果是保护或者私有,那么在外部你就不能使用该操作符了.以下是例子
class a
{
public:
bool operator<(const Person& b){return true;}
};
a a1,a2;
bool bRet = a1 < a2 ; 正确
-------------------------------------------------------------------------------------
class a
{
protected:
bool operator<(const Person& b){return true;}
};
a a1,a2;
bool bRet = a1 < a2 ; 错误
-----------------------------------------------------------------------------------------
class a
{
public:
friend bool operator<(const Person& a,const Person& b);//加了friend表示该函数不是成员函数了,顺便说一下 你上面的例子中,既然加了friend就不能再这里实现,所以{ return true;}是错误的写法
};
bool operator<(const Person& a,const Person& b){return true;}
a a1,a2;
bool bRet = a1 < a2 ; 正确
------------------------------------------------------------------------------------------
class a
{
protect:
friend bool operator<(const Person& a,const Person& b);
int a; // 假定下面的操作符要访问 保护成员变量a 如果是保护函数也一样
};
bool operator<(const Person& a,const Person& b){ return a.a > b.a;} //这里访问了保护成员a
a a1,a2;
bool bRet = a1 < a2 ; 错误 因为函数内部访问了 保护成员a
-------------------------------------------------------------------------------------------
class a
{
friend bool operator<(const Person& a,const Person& b);// 这里友元了操作符函数
protect:
int a; // 假定下面的操作符要访问 保护成员变量a 如果是保护函数也一样
};
bool operator<(const Person& a,const Person& b){ return a.a > b.a;} //这里访问了保护成员a
a a1,a2;
bool bRet = a1 < a2 ; 正确,因为该操作符被类a友元了,所以即使内部访问了类的属性也正确
friend 声明该函数是类的友元,可以访问私有成员,用friend可以避免用类名加点调用函数,这比较麻烦,还有friend只能在类内,不能在类外再加,否则会报错