简体   繁体   English

C ++错误:基本功能受到保护

[英]C++ error: base function is protected

I would like to know why the following code does not compile: 我想知道为什么以下代码无法编译:

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: 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

This code was adapted from here and I see no one complaining about that at the discussion forum. 这段代码是从这里改编而来的,我看到没有人在讨论论坛上抱怨这个。 Also, I'm using g++ 4.7.2 and the same code compiles and links fine with egcs-2.91.66. 另外,我正在使用g ++ 4.7.2,相同的代码编译并与egcs-2.91.66良好链接。

The specification of protected access states that pointer to members have to be formed either through the derived type (ie derived::... ) or a type inherited from it. 受保护访问的规范指出,必须通过派生类型(即derived::... )或从其继承的类型来形成指向成员的指针。 You can't name function_impl directly through base . 你不能直接通过base命名function_impl

That means that in your case you have to do it as 这意味着在你的情况下你必须这样做

operator function_type() const {
  return boolean_test() == true ? &derived::function_impl : 0;
}

Note that even if you use &derived::function_impl expression to obtain the address, the type of the result is still void (base::*function_type)() const , since the name function_impl in this case resolves to the function of base class. 请注意,即使您使用&derived::function_impl表达式来获取地址,结果的类型仍然是void (base::*function_type)() const ,因为在这种情况下,名称function_impl解析为base类的函数。

If it used to compile in some specific compiler (or some specific version of it), it simply means that that compiler allowed the error to slip through, which is what probably explains the code at the link. 如果它曾经在某些特定的编译器(或它的某个特定版本)中进行编译,那么它只是意味着该编译器允许错误传递,这可能解释了链接中的代码。

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

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