- class Coo
- {
- public:
- Coo() : a(0)
- {}
- int getA() const //常量成员函数
- {
- ++a; //编译错误
- return this->a;
- }
- private:
- int a;
- };
这段代码当然编译不过去。但下面这一段呢?
- class Coo2
- {
- public:
- Coo2() : p(new int(0)) {}
- ~Coo2() {delete p;}
- int const * getP() const //常量成员函数
- {
- *p = 1; //编译OK
- return this->p;
- }
- private:
- int* p;
- };
答案是编译得过去,原因是代码也正确。在语义上,Coo2对象,拥有的是指针,而不是指针所指向的东西。:)
如果您想与我交流,请点击如下链接成为我的好友:
http://student.youkuaiyun.com/invite.php?u=112600&c=f635b3cf130f350c