我想知道为什么下面的代码不能编译:
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
此代码改编自here我在论坛上看到没有人提示这一点。另外,我使用的是 g++ 4.7.2,相同的代码可以编译并链接到 egcs-2.91.66。
最佳答案
protected 访问的规范指出,指向成员的指针必须通过派生类型(即 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
类的函数。
如果它曾经在某些特定的编译器(或它的某些特定版本)中编译,则仅表示该编译器允许错误通过,这可能是链接中代码的解释。
关于C++ 错误 : base function is protected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16971065/