C++ 错误 : base function is protected

标签 c++ g++

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

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/

相关文章:

c++ - 将一个结构写成二进制,其中一个成员是一个字符串?

gcc - 由于 gcc 编译器版本不受支持,Caffe 编译失败

c++ - 为什么在这种情况下 g++ 不遵守一项定义规则 (ODR)? 。

c++ - 数据流管理 : Derived Form contains derived Bitmaps

c++ - 简单的 C++ getter/setter

c++ - 如何正确实现抽象类?

c++ - 类(class)成员重新排序

c++ - 覆盖默认的未处理异常行为

c++ - GCC/g++ cout << 与 printf()

c++ - 从 C/C++ 创建和删除文件