const關鍵字加以限定。const 可以用來修飾成員變量、成員函數以及對象。
class Student{
public:
Student(char *name, int age, float score);
void show();
//聲明常成員函數
char *getname() const;
int getage() const;
float getscore() const;
private:
char *m_name;
int m_age;
float m_score;
};
Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
cout<<m_name<<"的年齡是"<<m_age<<",成績是"<<m_score<<endl;
}
//定義常成員函數
char * Student::getname() const{
return m_name;
}
int Student::getage() const{
return m_age;
}
float Student::getscore() const{
return m_score;
}
getname()、getage()、getscore() 三個函數的功能都很簡單,僅僅是為了獲取成員變量的值,沒有任何修改成員變量的企圖,所以我們加了 const 限制,這是一種保險的做法,同時也使得語義更加明顯。char *getname() const和char *getname()是兩個不同的函數原型,如果只在一個地方加 const 會導致聲明和定義處的函數原型沖突。
const class object(params);
class const object(params);
const class *p = new class(params);
class const *p = new class(params);
class為類名,object為對象名,params為實參列表,p為指針名。兩種方式定義出來的對象都是常對象。
如果你對 const 的用法不理解,請猛擊《C語言const:禁止修改變量的值》。一旦將對象定義為常對象之後,不管是哪種形式,該對象就只能訪問被 const 修飾的成員了(包括 const 成員變量和 const 成員函數),因為非 const 成員可能會修改對象的數據(編譯器也會這樣假設),C++禁止這樣做。
#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 *m_name;
int m_age;
float m_score;
};
Student::Student(char *name, int age, float score): m_name(name), m_age(age), m_score(score){ }
void Student::show(){
cout<<m_name<<"的年齡是"<<m_age<<",成績是"<<m_score<<endl;
}
char * Student::getname() const{
return m_name;
}
int Student::getage() const{
return m_age;
}
float Student::getscore() const{
return m_score;
}
int main(){
const Student stu("小明", 15, 90.6);
//stu.show(); //error
cout<<stu.getname()<<"的年齡是"<<stu.getage()<<",成績是"<<stu.getscore()<<endl;
const Student *pstu = new Student("李磊", 16, 80.5);
//pstu -> show(); //error
cout<<pstu->getname()<<"的年齡是"<<pstu->getage()<<",成績是"<<pstu->getscore()<<endl;
return 0;
}
本例中,stu、pstu分別是常對象以及常對象指針,它們都只能調用 const 成員函數。