在类成员函数的声明和定义中,
const的函数体内部不能对其数据成员进行修改操作。从而达到了保护数据防止数据被任意修改的作用
const的对象,不能引用非const的成员函数。
#include <iostream>
using namespace std;
class number{
int num=1;
public:
void print() const {
num++; //这就是错的,因为不能修改类的数据成员
cout<<num<<endl;
}
};
int main() {
number n;
n.print();
}
本文探讨了C++中const关键字如何限制类的const成员函数修改数据成员。理解const对象不能调用非const成员函数的重要性,通过实例说明const函数体内的数据成员修改限制。
99

被折叠的 条评论
为什么被折叠?



