繁体   English   中英

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

如果它曾经在某些特定的编译器(或它的某个特定版本)中进行编译,那么它只是意味着该编译器允许错误传递,这可能解释了链接中的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM