[英]const and non const getter : C2248: cannot access private member declared in class
I have a class which implements a getter to an std::vector
. 我有一个实现std::vector
的getter的类。 Derived classes are allowed to change the content of the vector, while any other class may read it (or make a copy in my case), but not change it. 允许派生类更改向量的内容,而其他任何类都可以读取它(或复制本例),但不能更改。
SSCCE with Visual Studio 2010 (but should compile with any other as well). 具有Visual Studio 2010的SSCCE(但也应与其他任何版本一起编译)。
So in the base class I implemented the getter like this: 因此,在基类中,我像这样实现了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;
}
But I get the error 但是我得到了错误
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'
and I don't really see what is wrong with that and why the compiler doesn't take the public version which is const and instead insists on the non-const. 我真的不明白这有什么问题,为什么编译器不采用const的公共版本,而是坚持使用非const。
Even if I change the variable to const &s
(which wouldn't help in this case) I still get the same error. 即使我将变量更改为const &s
(在这种情况下也无济于事),我仍然会遇到相同的错误。
Edited the SSCCE for calling const and non const functions. 编辑了用于调用const和非const函数的SSCCE。
In this case it should be 在这种情况下,应该
const Y y;
in Z::my_function
for call const
version of function. 在Z::my_function
用于调用const
版本的函数。 Live Or just cast to const Y
, like Live或仅强制转换为const Y
,例如
std::vector<std::string> s = const_cast<const Y&>(y).getChilds();
Your case don't work, since access check will be applied only after overload resolution, in call y.getChilds()
non-const overload will be picked, since it has the best match. 您的情况不起作用,因为仅在重载解析之后才应用访问检查,因此在调用y.getChilds()
中将选择非const重载,因为它具有最佳匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.