我想知道为什么下面的代码不能编译:
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++
output:
~/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 http://www.artima.com/cppsource/safebool.html我在论坛上没有看到有人对此抱怨。另外,我使用 g++ 4.7.2,相同的代码可以与egcs-2.91.66 一起编译和链接。
受保护访问的规范规定,指向成员的指针必须通过派生类型(即,derived::...
) 或从它继承的类型。你不能说出名字function_impl
直接通过base
.
这意味着在你的情况下你必须这样做
operator function_type() const {
return boolean_test() == true ? &derived::function_impl : 0;
}
请注意,即使您使用&derived::function_impl
表达式获取地址,结果的类型仍然是void (base::*function_type)() const
,从名字起function_impl
在这种情况下解析为函数base
class.
如果它用于在某些特定编译器(或其某些特定版本)中进行编译,则仅意味着该编译器允许错误溜走,这可能解释了链接中的代码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)