Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么可以';我是否使用受保护/私有继承访问派生实例中基类的受保护成员?_C++_Inheritance_Protected - Fatal编程技术网

C++ 为什么可以';我是否使用受保护/私有继承访问派生实例中基类的受保护成员?

C++ 为什么可以';我是否使用受保护/私有继承访问派生实例中基类的受保护成员?,c++,inheritance,protected,C++,Inheritance,Protected,我认为基类的受保护成员可以被派生类的实例访问(或者从派生类派生的任何类,只要它们公开继承自后者) 但是在下面的清单中,当我尝试这样做时,会出现一个错误。那么我错过了什么 class Base{ private: virtual void f(){cout << "f of Base" << endl;} public: virtual ~Base(){} virtual void g(){this->f();} virtual void h(){c

我认为基类的受保护成员可以被派生类的实例访问(或者从派生类派生的任何类,只要它们公开继承自后者)

但是在下面的清单中,当我尝试这样做时,会出现一个错误。那么我错过了什么

class Base{
private:
  virtual void f(){cout << "f of Base" << endl;}

public:
  virtual ~Base(){}
  virtual void g(){this->f();}
  virtual void h(){cout << "h of Base "; this->f();}
};

class Derived: protected Base{
public:
  virtual ~Derived(){}
  virtual void f(){cout << "f of Derived" << endl;}
private:
  virtual void h(){cout << "h of Derived "; this->f();}
};

int main(){
  Base *base = new Base();
  cout << "Base" << endl;
  base->g(); //f of Base
  base->h(); //h of Base f of Base

  Derived *derived = new Derived();
  cout << "Derived" << endl;
  derived->f(); //f of Derived
  derived->g(); //this doesn't compile and I get the error "void Base::g() is inaccessible within this context". Why?
  derived->h(); //this doesn't compile given that h is private in Derived

  delete base;
  delete derived;
  return EXIT_SUCCESS;
}
类基{
私人:

虚拟无效f(){cout由于
派生的
继承自
基本的
受保护的
ly,基本的的所有公共成员在
派生的
中都是
受保护的
。这意味着,在
派生的
之外(例如在
中),这些成员的名称不可见

[…]如果使用
受保护的
访问说明符将一个类声明为另一个类的基类,则基类的公共成员和受保护成员可以作为派生类的受保护成员进行访问。[…]

类的成员可以是

(1.2)protected;也就是说,它的名称只能由声明它的类的成员和朋友、从该类派生的类及其朋友使用(请参见[class.protected])


当您声明
protected
继承
Base
by
Derived
时,如下所示

class Derived: protected Base
基本上,您正在使派生类的
Base
受保护的
成员的任何公共方法成为公共方法

class Derived: public Base
您会发现您可以访问
派生->g()
很好

派生->g()

可以通过将继承更改为公共来访问

派生->h()


可以通过将派生类内的访问说明符从private更改为public来访问(由于派生类指针指向其成员函数,因此仍然保持继承受保护)

为什么在此处使用虚拟继承?相关:语法错误,并不意味着在继承子句中包含virtual。我将修复itderived->h(),您不能访问类外的私有成员;在派生类中,成员函数被声明为私有。是的,已经尝试过了,并且效果很好,我只是忘记了我实际上在主函数中调用g(),因此出现了错误。无论如何,谢谢!很高兴为您提供帮助;)