c++错误:基函数受保护
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
类的函数。
如果它用于在某个特定的编译器(或它的某个特定版本)中编译,它只是意味着该编译器允许错误通过,这可能就是解释链接中的代码的原因。
相关文章:
- 继承和友元函数,从基类访问受保护的成员
- 为什么继承的受保护构造函数不能公开?
- 基类中受保护的纯虚函数如何被基类的友元类使用?
- 在派生类中具有相同签名但继承为受保护的函数
- 在派生类的构造函数初始化中无法访问受保护的函数
- 无法访问派生类函数内的基类的受保护数据成员
- 更改了C 17中受保护构造函数的规则
- C++获取指向受保护覆盖函数的指针
- 我可以安全地转换为兄弟类来包装受保护的函数吗
- 继承受保护的函数和公共变量C++时发生多重继承编译错误
- 检测(可能是抽象的)基类的受保护构造函数
- 从另一个类 C++ 访问受保护的函数
- 声明受保护的函数friend
- 访问基类的受保护构造函数
- 受保护的函数不需要虚拟
- 派生类中的静态方法可以调用c++中的受保护构造函数吗?
- 派生类中的成员不能使用c++受保护的函数
- C++继承和受保护基类成员的访问:用Java风格做这件事是个坏主意吗
- 从派生的友元函数调用受保护的函数
- 从派生类访问受保护的函数