close

Operator overloading allows the programmer to define how operators (such as +, -, ==, =, and !) should interact with various data types. 

Because operators in C++ are implemented as functions, operator overloading works very analogously to function overloading.

for example :

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;
}

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

    KwCheng's blog

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