close

在物件導向中 , 我們是以物件的方式來進行programming , 

而對於我們所建立的這些物件 ,  我們可能會想對他們進行一些物件之間的運算 , 

像string + string 就是concatenation 的意思.

為了因應這樣的狀況 , 我們就需要對一些operator進行overloading的動作.

First , we will talk about : overloading the arithmetic operators ,

在operator overloading中 , 如果我們並不會modify到物件內容的話 , 那最直接的方式就是將這個operator function

宣告為friend function. (這樣便可以對private member data進行存取)

 

以下便是對addition進行operloading的方法 , 因為addition是一個二元運算子 , 

所以我們必須給他兩個parameter , 對這兩個參數進行運作後 , 再執行回傳.

而當然 , 兩個相同的物件相加 , 一定還是相同的物件 , 所以回傳的物件type同樣也是Cent.

 

class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // Add Cents + Cents
    friend Cents operator+(const Cents &c1, const Cents &c2);
 
    int GetCents() { return m_nCents; }
};
 
// note: this function is not a member function!
Cents operator+(const Cents &c1, const Cents &c2)
{
    // use the Cents constructor and operator+(int, int)
    return Cents(c1.m_nCents + c2.m_nCents);
}
 
int main()
{
    Cents cCents1(6);
    Cents cCents2(8);
    Cents cCentsSum = cCents1 + cCents2;
    std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl;
 
    return 0;
}

而在- , * , / 基本上也是類似的方式.

Cents operator-(const Cents &c1, const Cents &c2)
{
    // use the Cents constructor and operator-(int, int)
    return Cents(c1.m_nCents - c2.m_nCents);
}
 

 


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

    KwCheng's blog

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