Const用法总结
1. 把一个const对象的地址赋给一个普通的、非const对象的指针会导致编译时的错误。
const double pi = 3.14;
double *ptr = π // error: ptr is a plain pointer
const double *cptr = π // OK: cptr is a pointer to const
2. const修饰变量
const int nvalue;
int const nvalue; //同一个含义,都是nvalue不可变。
3. const修饰指针
-
#include <iostream>
-
using namespace std;
-
int main()
-
{
-
char a = 10;
-
const char *p1 = &a;
-
char const *p2 = &a;
-
char *const p3 = &a;
-
-
//(*p1)++; // error, the value of p1 is constant
-
p1++; // OK, p1 canchange
-
//(*p2)++; // error, the same as p1
-
p2++; // OK, the sameas p1
-
(*p3)++; // OK, the valueof p3 can change
-
//p3++; // error, p3 is constant
-
a++; // OK, wecannot change value by pointer, but we can change by this.
-
return 0;
-
}
p1和p2相同,表示指针指向的值不可变,简称指常针,虽然不能通过p1,p2修改变量,但变量本身可以修改,比如可以改变a,但不能通过指常针改变变量的值;而p3表示指针不可变,指针指向a之后不能再指向别的地址,简称常指针。
4. const修饰成员函数
在调用成员函数时,都有1个额外的、隐含的形参this。在调用成员函数时,形参this初始化为调用函数的对象的地址。如下面的语句:
class A
{…
void func(int ) const;
…} a;
a.func(para);
就如编译器这样重写这个函数调用:
A::func(&a, para);
这里的&a相当于this指针。在普通的非const成员函数中,this的类型是1个指向类类型的const指针。可以改变this所指向的值,但不能改变this所保存的地址。在const成员函数中,this的类型是一个指向const类类型的const指针。既不能改变this所指向的对象,也不能改变this所保存的地址。即在func里无法修改对象a。用const修饰函数的目的其实就是起到一种只读的作用,任何试图修改对象的动作都会在编译时报错。
另外,在类定义时,const成员函数不能调用任何非const类型的函数,如下述代码:
-
#include <iostream>
-
using namespace std;
-
-
class Demo
-
{
-
private:
-
int value;
-
public:
-
Demo(int val = 0) : value(val){}
-
void Set(int val)
-
{
-
value = val;
-
}
-
void Test(){}
-
int Get() const
-
{
-
Test();
-
return value;
-
}
-
};
-
-
int main(int argc, char **argv)
-
{
-
-
return 0;
-
}
-
在const函数Get()中调用非const函数Test(),编译时会报错,原因是Get()已经声明为const,即this指针所指向的对象不能发生变化,在里面又调用了Test()函数,但不能保证Test()函数不修改该对象,即在Test函数中可能发生修改对象的动作,而这与this指针的const特性违背,所以错误消息其实是不能转换this指针,因为编译器在默认情况下不能改变this指针的const特性。