在类中,假如你不希望某些数据被修改,可以使用const关键字加以限定。const 可以用来修饰成员变量和成员函数。
const 成员变量只要要在公告时加上 const 关键字。
初始化 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() constchar *getname()
是两个不同的函数原型,假如只在一个地方加 const 会导致公告和定义处的函数原型冲突。
注意:
1、函数开头的 const 用来修饰函数的返回值,表示返回值是 const 类型,也就是不能被修改,如const char * getname()。
2、函数头部的结尾加上 const 表示常成员函数,这种函数只能读取成员变量的值,而不能修改成员变量的值,如char * getname() 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 成员可能会修改对象的数据(编译器也会怀疑)。