[英]const and non const getter : C2248: cannot access private member declared in class
我有一个实现std::vector
的getter的类。 允许派生类更改向量的内容,而其他任何类都可以读取它(或复制本例),但不能更改。
具有Visual Studio 2010的SSCCE(但也应与其他任何版本一起编译)。
因此,在基类中,我像这样实现了getter:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
class X
{
public:
inline std::vector<std::string> const &getChilds(void) const
{
return mChilds;
}
void mutateInternal(void)
{
mState != mState;
}
protected:
inline std::vector<std::string> &getChilds(void)
{
return mChilds;
}
private:
std::vector<std::string> mChilds;
bool mState;
};
// Now in the derived class
class Y : public X
{
public:
Y(void)
{
std::vector<std::string> &childs = getChilds();
childs.push_back("Test");
}
};
// In the non derived class:
class Z
{
public:
void myfunction(void)
{
Y y;
std::vector<std::string> s = y.getChilds();
if(s.size() == 0)
y.mutateInternal();
}
};
int main(int argc, char *argv[])
{
return 0;
}
但是我得到了错误
1>junk.cpp(49): error C2248: "X::getChilds": cannot access private member declared in class.
1> junk.cpp(18): Siehe Deklaration von 'X::getChilds'
1> junk.cpp(10): Siehe Deklaration von 'X'
我真的不明白这有什么问题,为什么编译器不采用const的公共版本,而是坚持使用非const。
即使我将变量更改为const &s
(在这种情况下也无济于事),我仍然会遇到相同的错误。
编辑了用于调用const和非const函数的SSCCE。
在这种情况下,应该
const Y y;
在Z::my_function
用于调用const
版本的函数。 Live或仅强制转换为const Y
,例如
std::vector<std::string> s = const_cast<const Y&>(y).getChilds();
您的情况不起作用,因为仅在重载解析之后才应用访问检查,因此在调用y.getChilds()
中将选择非const重载,因为它具有最佳匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.