const

来源:互联网 发布:linux自启动脚本编写 编辑:程序博客网 时间:2024/05/01 16:58

1 const与指针

 分为两种情况 ①指针所指向的数据时const,不能修改。②指针为const不能修改。

   ① const int *p;(int cont *p)。*p  为const类型

   ②int* const p=&i;//int i    p为const类型 ,初始化赋值,以后不能修改。


2const与类成员函数

  当类成员函数为const类型时候,则此const类成员函数不能修改成员数据,也不能调用类内的其他非const函数。

#include <iostream>using namespace std;class Plant{public:void watering() const{//(const_cast<Plant*>(this))->hello();hello();//error   const成员函数不能修改类数据成员count++;//error const成员函数不能调用非const函数} void hello() { cout << "hello" ;}private: int count;};void main(){Plant *p=new Plant;p->watering();//watring 的this指针,是const类型的指针,所以不能修改任何数据}
目的是:可以使成员数的意义更加清楚。

非const成员函数不能被const成员函数调用,原因是非const成员函数可能企图修改对象数据成员。


如上面程序,如果const成员函数 非要修改对象数据成员。有两种方法,一种是在数据成员前 添加mutable。

另一种是把 this指针的const性质去掉。使用 const_cast 显式类型转换。

因为对象调用watering的时候,传入的是一个 const指针。

(const_cast<Plant*>(this))->hello();


0 0
原创粉丝点击