Pin-Jiun / Programming-Language-CPP

It's the note/experience about C++, and I have the basic ability of C.
0 stars 0 forks source link

11-Operator Overloading #14

Open Pin-Jiun opened 1 year ago

Pin-Jiun commented 1 year ago

operator overloading運算子多載

對於系統的所有操作符,一般情況下,只支援基本資料型別和標準庫中提供的class,對於使用者自己定義的class,如果想支援基本操作,則需要使用者自己來定義關於這個操作符的具體實現。

class Person{
public:
    int money;
};

int main()
{
    Person Amy;
    Amy.money=100;
    Person Bob;
    Bob.money=200;
}

比如,要將兩人直接相加算出其共同有的錢int total = (Amy+Bob);則需進行實作operator overloading returntype operator +(...)

class Person{
public:
    int money;
};

int operator +(const Person & person1, const Person & person2){
    int r = person1.money+person2.money;
    return r;
}

int main()
{
    Person Amy;
    Amy.money=100;
    Person Bob;
    Bob.money=200;
    int total = (Amy+Bob);
    cout << total << endl;
}

參考資料https://www.itread01.com/article/1483834698.html