[英]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.