6. C++ 中的cosnt
在類中,如果你不希望某些資料被修改,可以使用const關鍵字加以限定。const 可以用來修飾成員變數和成員函式。
6.1 const成員變數
const 成員變數只需要在宣告時加上 const 關鍵字。
初始化 const 成員變數只有一種方法,就是通過建構函式的初始化列表。
6.2 const成員函式(常成員函式)
const 成員函式可以使用類中的所有成員變數,但是不能修改它們的值,這種措施主要還是為了保護資料而設定的。
我們通常將 get 函式設定為常成員函式。讀取成員變數的函式的名字通常以get開頭,後跟成員變數的名字,所以通常將它們稱為 get 函式。
常成員函式需要在宣告和定義的時候在函式頭部的結尾加上 const 關鍵字,例如:
#include <iostream> using namespace std; class Student{ public: Student(char *name, int age, float score); void show(); //宣告常成員函式 char *getname() const; int getage() const; float getscore() const; private: char *name; int age; float score; }; Student::Student(char *name, int age, float score): name(name), age(age), score(score){ } void Student::show(){ cout<<name<<"的年齡是"<<age<<",成績是"<<score<<endl; } //定義常成員函式 char * Student::getname() const{ return name; } int Student::getage() const{ return age; } float Student::getscore() const{ return score; } int main() { return 0; }
必須在成員函式的宣告和定義處同時加上 const 關鍵字。
char *getname() const char *getname()
是兩個不同的函式原型,如果只在一個地方加 const 會導致宣告和定義處的函式原型衝突。
注意:
1、函式開頭的 const 用來修飾函式的返回值,表示返回值是 const 型別,也就是不能被修改,如const char * getname()。
2、函式頭部的結尾加上 const 表示常成員函式,這種函式只能讀取成員變數的值,而不能修改成員變數的值,如char * getname() const。
6.3 const物件(常物件)
定義常物件的語法和定義常量的語法類似:
const類名物件名(引數); 類名const 物件名(引數);
當然你也可以定義 const 指標:
const 類名 *變數 = new 類名(引數); 類名 const *變數 = new 類名(引數);
例項
#include <iostream> using namespace std; class Student{ public: Student(char *name, int age, float score); public: void show(); char *getname() const; int getage() const; float getscore() const; private: char *name; int age; float score; }; Student::Student(char *name, int age, float score): name(name), age(age), score(score){ } void Student::show(){ cout<<name<<"的年齡是"<<age<<",成績是"<<score<<endl; } char * Student::getname() const{ return name; } int Student::getage() const{ return age; } float Student::getscore() const{ return score; } int main(){ const Student stu("豆豆", 12, 85.0); //stu.show(); //error cout<<stu.getname()<<"的年齡是"<<stu.getage()<<",成績是"<<stu.getscore()<<endl; const Student *pstu = new Student("哈哈", 16, 65.0); //pstu -> show(); //error cout<<pstu->getname()<<"的年齡是"<<pstu->getage()<<",成績是"<<pstu->getscore()<<endl; return 0; }  一旦將物件定義為常物件之後,該物件就只能訪問被 const 修飾的成員了(包括 const 成員變數和 const 成員函式),因為非 const 成員可能會修改物件的資料(編譯器也會懷疑)。