close

要進行operator overloading , 一般來說有兩種形式 , 分別是non-member function 以及 nonstatic member function .

non-member function一般來說較為容易理解 , 但是若要讓他能夠存取class內的private data , 則要將他宣告為friend function.

But ..writing friend functions that modify private member variables of a class is generally not considered good coding style, as it violates encapsulation.

Follow is the example of these two methods.

non-member function :

class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // Overload cCents + int
    friend Cents operator+(Cents &cCents, int nCents);
 
    int GetCents() { return m_nCents; }
};
 
// note: this function is not a member function!
Cents operator+(Cents &cCents, int nCents)
{
    return Cents(cCents.m_nCents + nCents);
}

nonstatic member function
class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // Overload cCents + int
    Cents operator+(int nCents); // 可以想成是把int當做argument傳入給cCents
 
    int GetCents() { return m_nCents; }
};
 
// note: this function is a member function!
Cents Cents::operator+(int nCents)
{
    return Cents(m_nCents + nCents);
}

 

ref : http://www.learncpp.com/cpp-tutorial/96-overloading-operators-using-member-functions/

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()