我想知道为什么以下代码无法编译:
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[]) {
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这段代码是从这里改编而来的,我看到没有人在讨论论坛上抱怨这个.另外,我正在使用g ++ 4.7.2,相同的代码编译并与egcs-2.91.66良好链接.
AnT*_*AnT 10
受保护访问的规范指出,必须通过派生类型(即derived::...)或从其继承的类型来形成指向成员的指针.你无法function_impl直接命名base.
这意味着在你的情况下你必须这样做
operator function_type() const {
return boolean_test() == true ? &derived::function_impl : 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,即使您使用&derived::function_impl表达式来获取地址,结果的类型仍然是void (base::*function_type)() const,因为function_impl在这种情况下,名称解析为base类的函数.
如果它曾经在某些特定的编译器(或它的某个特定版本)中进行编译,那么它只是意味着该编译器允许错误传递,这可能解释了链接中的代码.