继续const用法

来源:互联网 发布:湖南教师网络研修平台 编辑:程序博客网 时间:2024/06/08 19:20

const可以用在类型前面,也可以用在变量前面,比如看下面一段代码:

#include <iostream>using namespace std;int main(){int a=5,b=6;const int *p1=&a;int * const p2=&a;const int* const p3=&a;/* 自身值和指向的值都不可改变 */a=6;    /* a是一个变量,可以重新赋值 */*p1=2;  /* p1指向的值不可改变, 编译出错 */p1=&b;  /* p1指向的值不可改变,p1本身的值可以改变(附带效果p1指向的值改变了) */p2=&b;  /* p2的值不可改变,编译出错 */*p2=3;  /* p2指向的值非const,可以修改没有问题 */return 0;}
注释很清楚了,再举一个关于p3的例子:类的常成员函数。代码如下:

void func2(int a, int b) const;

假设func2是某个类的常成员函数,大家都知道这个const修饰的是this指针,那么const是如何修饰这个this指针的?是p1的方式、p2的方式‘还是p3的方式。我们使用具体代码证明一下:

.h文件

#pragma onceclass test{public:int m_a;int m_b;public:void func1(int a, int b);void func2(int a, int b) const;};
.cpp文件,只看func2函数实现

void test::func2(int a, int b) const{cout<<"this="<<this<<endl;cout<<"(*this).m_a="<<(*this).m_a<<endl;cout<<"(*this).m_b="<<(*this).m_b<<endl;this++;(*this).m_b=b;cout<<"this="<<this<<endl;cout<<"(*this).m_a="<<(*this).m_a<<endl;cout<<"(*this).m_b="<<(*this).m_b<<endl;}
main.cpp文件

int main(){test *a=new test;a->func1(1,1);a->func2(2,3);delete a;return 0;}
编译时出错,看出错原因


很明显this常量,this所指向的值也是常量。const不仅修饰了this还修饰了类的类型。常成员成员函数展开来写应该是:

void func2(int a, int b, const test* const this);




原创粉丝点击