2020年8月13日 星期四

const member function && const static function

class 的 object 也能像 int, double 等資料型態一樣,被宣告成 const,這代表該object的資料不能被任意更動。
因此只有不會更動到資料的函式,也就是const member function能被這種const object呼叫。

宣告const member function的語法就是在()與{}間加上const:

class ID{
private:
    string name;
public:
    ID(string n){name=n;}
    string getName() const {return name;}
};

這樣一來,如果要在getName()這個函式修改值,像是把name="unknown"的話,就會出現編譯錯誤的訊息。

另外,由於const object不能使用一般的 member function,但 const object 跟 non-const object 都能使用 const member function,在寫某些不會更動值的函式像是accessor時,可以直接加個const。

參考:
https://www.geeksforgeeks.org/const-member-functions-c/


_______________________

static 通常不會單獨出現,而是配合著 const 。
宣告也是在外面,不過是 const + data type 一起。
class CScore { 
protected:
    //declare a static constant
    static const int Max;
};
const int CScore::Max = 100; //outside class

沒有留言:

張貼留言