为什么返回对指向的成员变量的引用有效,而另一个则无效?我知道一个const
成员函数应该只返回const
引用,但是为什么对于指针来说这似乎不正确呢?
class MyClass
{
private:
int * a;
int b;
public:
MyClass() { a = new int; }
~MyClass() { delete a; }
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; } // obviously bad
};
int main(void)
{
MyClass m;
m.geta() = 5; //works????
m.getb() = 7; //doesn't compile
return 0;
}
int & geta(void) const { return *a; } // good?
int & getb(void) const { return b; } // obviously bad
在 const 函数中,每个数据成员都变成 const以使其无法修改的方式. int
变成const int
, int *
变成int * const
, 等等。
自从type of a
在你的第一个函数中变成int * const
,相对于const int *
,这样您就可以更改数据(可修改):
m.geta() = 5; //works, as the data is modifiable
之间的区别:const int*
and int * const
.
-
const int*
表示指针是非常量,但是指针指向的数据是const.
-
int * const
表示指针是const,但是指针指向的数据是非常量.
你的第二个函数尝试返回const int &
,自从type of b
become const int
。但是您在代码中提到了实际的返回类型int &
,所以这个函数会not甚至编译(参见this http://www.ideone.com/xjE8E),无论你在做什么main()
,因为返回type不匹配。这是修复方法:
const int & getb(void) const { return b; }
Now it 编译得很好! http://www.ideone.com/J2eLN.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)