繁体   English   中英

受C ++保护的ctor不适用于派生类中的成员

[英]C++ protected ctor not available to members in derived class

如果我声明一个派生类,其中也包括基本类型的其他成员, "constructor is protected"出现"constructor is protected"错误。

test.cpp:

class Base { protected: Base() {} };

class Derived1 : public Base
  {
    Derived1()  {}
  };

class Derived2 : public Base
  {
    Derived2()  {}
    Base    other_base;
  };

$ g ++ test.cpp

test.cpp: In constructor ‘Derived2::Derived2()’:
test.cpp:3:25: error: ‘Base::Base()’ is protected
 class Base { protected: Base() {} };
                         ^
test.cpp:12:14: error: within this context
  Derived2()  {}

如果我将Derived2声明为Base的朋友,则错误消失了。 谁能解释这里发生了什么?

TIA。

这是因为other_base实际上不是Derived2类的一部分,它是一个单独的对象,遵循公共/受保护/私有成员的常规规则。

问题在于Derived2包含Base的实例。

受保护成员的可访问性仅在派生类实例访问其继承的成员的上下文中。 它不允许使用受保护的构造函数构造成员。

因此, Derived2的构造方法无法构造other_base ,但可以构造其继承的Base

Derived2声明为Basefriend可以构建other_base

在您的示例中,other_base被视为Derived2类的成员,并且遵循正常的访问规则。 可以调用受保护的Base() ctor的唯一地方是Derived2 ctor的初始化列表:

Derived2():Base(){}

如果您要使用受保护的/私有方法/成员,请使用friend关键字。

暂无
暂无

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

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