[英]C++ error: base function is protected
我想知道為什么以下代碼無法編譯:
class base {
protected:
typedef void (base::*function_type)() const;
void function_impl() const {} // error: ‘void base::function_impl() const’ is protected
};
class derived: public base {
public:
operator function_type() const {
return boolean_test() == true ? &base::function_impl : 0; // error: within this context
}
protected:
virtual bool boolean_test() const = 0;
virtual ~derived() {}
};
int main(int argc, char* argv[]) {
}
g++
輸出:
~/protected_test$ g++ src/protected_test.cpp
src/protected_test.cpp: In member function ‘derived::operator base::function_type() const’:
src/protected_test.cpp:4:8: error: ‘void base::function_impl() const’ is protected
src/protected_test.cpp:10:44: error: within this context
這段代碼是從這里改編而來的,我看到沒有人在討論論壇上抱怨這個。 另外,我正在使用g ++ 4.7.2,相同的代碼編譯並與egcs-2.91.66良好鏈接。
受保護訪問的規范指出,必須通過派生類型(即derived::...
)或從其繼承的類型來形成指向成員的指針。 你不能直接通過base
命名function_impl
。
這意味着在你的情況下你必須這樣做
operator function_type() const {
return boolean_test() == true ? &derived::function_impl : 0;
}
請注意,即使您使用&derived::function_impl
表達式來獲取地址,結果的類型仍然是void (base::*function_type)() const
,因為在這種情況下,名稱function_impl
解析為base
類的函數。
如果它曾經在某些特定的編譯器(或它的某個特定版本)中進行編譯,那么它只是意味着該編譯器允許錯誤傳遞,這可能解釋了鏈接中的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.