The first is defined as Class Member overload operator , the second is a Nonmember overload operator .When Nonmember function accesses the private member
private:
int m_nCents;
, friend
should be added.Even I change to public:int m_nCents;
,it does not work.friend
seems to be a rule, not because of member access limitation. But you can move the Nonmember operator out of class body and access public member variable. Any better idea?I feel confused. I think that ALL Nonmember operator(have same parameter number with operand and can not be called as a member function ) must be declared as friend
in class body.
>
is a binary operator which have two parameter for each operand. You have found that the Class Member overload operator >
only have one explicit parameter and an implicit this
parameter. Nonmember operator must have two.
class Cents{
private:
int m_nCents;
public:
Cents(int nCents)
: m_nCents(nCents)
{
}
friend bool operator>(Cents &c1, Cents&c2); //Nomember
bool operator<(Cents &c1); //class member
};
bool operator>(Cents &c1, Cents&c2) // <--- why friend?
{
//cout << "in >" << endl;
return (c1.m_nCents > c2.m_nCents) ? true: false;
}
bool Cents::operator<(Cents &c1)
{
//cout << "in <" << endl;
return (this->m_nCents < c1.m_nCents) ? true: false;
}
int main(){
//nomember
//if(poor.operator>(rich)) //compiler error
if(poor > rich){
cout << "oh yeal!" << endl;
}
else
{
cout << "oh no!" << endl;
}
//member
//if(poor.operator<(rich)) //can call this way
if(poor.operator<(rich)){
cout << "oh yeal!" << endl;
}
else
{
cout << "oh no!" << endl;
}
}
I move implementations out of class body. Now you can see class member operator has a Cents::
qualifier just like member function.
? true : false
on boolean expressions, then remember that the result is also a boolean expression, so you should write((c1.m_nCents > c2.m_nCents) ? true : false) ? true : false)
. – Methuselah(((c1.m_nCents > c2.m_nCents) ? true : false) ? true : false) ? false == false : true != true
. Don't want those boolean expressions getting away from you. – Atlante