小编Tor*_*enC的帖子

子类是否真的继承了私有成员变量?

基本上据我所知,当你创建一个带有public,protected和private部分的基类以及每个public和protected部分中的变量/函数时,它们将被继承到子类的相应部分(由类子类定义) :私人基地,它将采取所有公共和受保护的基地成员并将其公开,将私人一词改为公开,将其全部公开,并将其更改为受保护,将其全部置于保护状态).

所以,当你创建一个子类时,你从来没有从前一个类的私有部分(在这种情况下是基类)中收到任何东西,如果这是真的那么子类的一个对象永远不应该拥有它自己的一个版本的私有变量或基类的函数是否正确?

让我们来看一个例子:

#include <iostream>

class myClass     // Creates a class titled myClass with a public section and a private section.
{
public:
  void setMyVariable();
  int getMyVariable();
private:
  int myVariable;     // This private member variable should never be inherited.
};

class yourClass : public myClass {};    // Creates a sub-class of myClass that inherits all the public/protected members into  the
// public section of yourClass. This should only inherit setMyVariable()
// and getMyVariable() since myVariable is private. This class …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance private members

12
推荐指数
5
解决办法
3万
查看次数

标签 统计

c++ ×1

inheritance ×1

members ×1

private ×1