c++错误:基函数受保护

C++ error: base function is protected

本文关键字:受保护 基函数 错误 c++      更新时间:2023-10-16

我想知道为什么下面的代码不能编译:

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类的函数。

如果它用于在某个特定的编译器(或它的某个特定版本)中编译,它只是意味着该编译器允许错误通过,这可能就是解释链接中的代码的原因。