【day0404 C++】類的成員函數

1、函數原型必須在類(class)中定義。

2、函數體:

*可以在類中定義函數體

*也可以在外部定義.

3、this指針.

4、const放後面修飾成員函數。


# 一般會把比較短小的函數體放在類中,把比較長的函數的函數體放外部。

# 也可以把函數體都放在外部,這樣看起來比較清晰。


Demo:

#include <iostream>
#include <string>
using namespace std;

/*類的成員函數*/

class SalesItem{

public:
        /// 外部成員函數,必須先聲明
        void printAverage() const;

        /// 類的內部成員函數
        bool isSameItem(const SalesItem &rhs) const{
            //this:當前對象,this是指針
            return (this->isbn == rhs.isbn);
        }

public:
        std::string isbn;   //書號
        unsigned allSold;   //銷量
        double revenue;     //收入
};

/// 外部成員函數,必須先聲明
void SalesItem::printAverage() const
{
    //this->isbn = "0000";  const放後面修飾,不能修改。
    cout << "** 平均 **\n";
}


int main()
{
    SalesItem item1, item2;

    item1.isbn = "201-7852-16";
    item1.allSold = 10;
    item1.revenue = 300.00;

    item2.isbn = "201-7852-16";
    item2.allSold = 15;
    item2.revenue = 450.00;

    if (item1.isSameItem(item2)){
        cout << "這兩個item是  一樣的!\n";
    }else{
        cout << "這兩個item是不一樣的!\n";
    }

    item1.printAverage();

    return 0;
}
輸出:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章