C++中const关键字无处不在,我这里做下汇总,作为工具文章方便翻阅。
一:修饰数据成员
修饰的成员一单定义初始化后不能再进行修改,如:
const int a = 10;
a =20; //重新赋值直接会报错
当修饰类的成员函数时,先来段错误的代码
1 2 3 4 5 6 7 8 9 10
| class Student { public: Student(int i) { this->age = i; //age是const类型直接复制会报错 } private: const int age; };
|
解决上面的错误有两种方法
方法一:
使用参数列表的形式(推荐使用)
1 2 3 4 5 6 7 8 9 10
| class Student { public: Student(int i):age(i) { }
private: const int age; };
|
方法二:
定义age时直接赋值
1 2 3 4 5 6 7 8
| class Student { public: Student ();
private: const int age = 20; };
|
二:修饰成员函数
在声明之后,实现体之前
格式为:
类型 函数名(参数….) const
const修饰的成员函数不能修改类中的成员函数,函数中只能调用const修饰的函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Student { public: Student (int i ):age(i) {
}
void update () const { age = age +1; //const 修饰的成员函数不能修改类中的成员变量 display(); //const 修饰的成员函数,函数中只能调用const修饰的成员函数 }
void display() { cout << "age:" << endl; } private: int age; };
|
三:修饰类对象
const修饰的对象,只能调用const修饰的成员函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Student { public: Student (int i ):age(i) {
}
void update () const { cout << "this is update" << endl; }
void display() { cout << "age:" << endl; } private: int age; };
int main() { const Student stu(30); stu.update(); stu.display(); //const修饰的类对象 只能调用const修饰的成员函数 return 1; }
|
成员函数有无const修饰可以构成重载,非const对象调用时优先调用非const修饰的成员函数,如不构成重载也可以调用const修饰成员函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Student { public: Student (int i ):age(i) {
}
void display() { cout << "void display()" << endl; }
void display() const { cout << "display() const" << endl; } private: int age; };
int main() { Student stu(30); stu.display();
return 1; }
|
输出结果: