假设class X我想要返回内部成员的访问权限:
class Z
{
// details
};
class X
{
std::vector<Z> vecZ;
public:
Z& Z(size_t index)
{
// massive amounts of code for validating index
Z& ret = vecZ[index];
// even more code for determining that the Z instance
// at index is *exactly* the right sort of Z (a process
// which involves calculating leap years in which
// religious holidays fall on Tuesdays for
// the next thousand years or so)
return ret;
}
const …Run Code Online (Sandbox Code Playgroud) 你有没有恨它
class Foobar {
public:
Something& getSomething(int index) {
// big, non-trivial chunk of code...
return something;
}
const Something& getSomething(int index) const {
// big, non-trivial chunk of code...
return something;
}
}
Run Code Online (Sandbox Code Playgroud)
我们无法使用另一个方法实现这两种方法,因为您无法const从const版本中调用非版本(编译器错误).演员将被要求const从非const一个版本调用该版本.
有没有一个真正优雅的解决方案,如果没有,最接近一个?
T& f() { // some code ... }
const T& f() const { // some code ... }
Run Code Online (Sandbox Code Playgroud)
我现在已经看过几次了(在我迄今为止研究的介绍性书中).我知道第一个const使返回值为const,换句话说:不可修改.我相信第二个const允许为const声明的变量调用该函数.
但是为什么你会在同一个类定义中同时拥有这两个函数?编译器如何区分这些?我相信第二个f()(带const)也可以调用非const变量.
为什么STL容器定义访问器的const和非const版本?
定义const T& at(unsigned int i) const而T& at(unsigned int)不仅仅是非const版本有什么好处?