C++ 中重載運算符 「<」 及 friend屬性

類中重載運算符不須要必定是成員函數,也能夠聲明爲友元函數。mvc

 
class person

{

public:

//做爲類的成員函數,重載運算符參數只須要右操做值便可
    bool operator<(const Person& arg);

private:

   int a;

};

//實現時須要類名限定

 bool person::operator<(const Person& arg)
{
    if( (this->a) < arg.a)
       return true;
    else
        return false;

}



person a1,a2;

bool bRet = a1 < a2 ; 正確
 
 

class person

{

public:

//做爲類的成員函數,重載運算符參數只須要右操做值便可
函數


   friend bool operator<(const Person& arg1, const Person& arg2);

private:

   int a;

};

//實現時不須要類名限定

 bool operator<(const Person& arg1, const Person& arg2)
{
    if( arg1.a < arg2.a)
       return true;
    else
        return false;

}
this


person a1,a2;

bool bRet = a1 < a2 ; 正確

在這個例子1中,運算符重載函數做爲類的成員函數,使用該類的對象時能夠調用內部的私有保護成員。spa

在例子2中,運算符重載函數雖然不是類的成員函數,可是被聲明爲類的友元函數,一樣能夠調用類內部的私有保護成員。code

可是將重載函數聲明爲保護或者私有函數,使用該類的對象時將沒法對重載函數進行調用,也就是 若是你把重載函數寫成成員函數或者友元函數,並且是public屬性,對於使用該操做符時其實沒有差異,可是若是是保護或者私有,那麼在外部你就不能使用該操做符了:對象

class person

{

protect: //做爲類的成員函數,重載運算符參數只須要右操做值便可
    bool operator<(const Person& arg);

private:

   int a;

};

//實現時須要類名限定

 bool person::operator<(const Person& arg)
{
    if( (this->a) < arg.a)
       return true;
    else
        return false;

}



person a1,a2;

bool bRet = a1 < a2 ; 錯誤
class person

{

protect: //做爲類的成員函數,重載運算符參數只須要右操做值便可


   friend bool operator<(const Person& arg1, const Person& arg2);

private:

   int a;

};

//實現時不須要類名限定

 bool operator<(const Person& arg1, const Person& arg2)
{
    if( arg1.a < arg2.a)
       return true;
    else
        return false;

}

person a1,a2;

bool bRet = a1 < a2 ; 錯誤
相關文章
相關標籤/搜索