小编nit*_*man的帖子

私人继承

我完全不懂这个:

class Base
{
    public:
    Base()
    {
        cout<<"Base" << endl;
    }

    virtual void call()
    {
        cout<<"Base call" << endl; 
    }
};

class Derived: private Base
{
    public:      
    Derived()
    {
        cout<<"Derived" << endl;
    } 
};

int main(void)
{
    Base *bPtr = new Derived(); // This is not allowed
}
Run Code Online (Sandbox Code Playgroud)

是因为有人可能使用bPtr调用call(),这实际上是在派生对象上完成的?或者还有其他原因吗?

c++ inheritance

7
推荐指数
3
解决办法
4543
查看次数

未调用基本复制构造函数

class Base
{
      public:
      int i;

      Base()
      {
          cout<<"Base Constructor"<<endl;
      }

      Base (Base& b)
      {
          cout<<"Base Copy Constructor"<<endl; 
          i = b.i; 
      }


      ~Base()
      {
          cout<<"Base Destructor"<<endl;
      }

      void val()
      {
             cout<<"i: "<< i<<endl;
      }      
};

class Derived: public Base
{
      public:
      int i;

      Derived()
      {
          Base::i = 5;     
          cout<<"Derived Constructor"<<endl;
      }

      /*Derived (Derived& d)
      {
          cout<<"Derived copy Constructor"<<endl;
          i = d.i; 
      }*/

      ~Derived()
      {
          cout<<"Derived Destructor"<<endl;
      }      

      void val()
      {
             cout<<"i: "<< i<<endl;
             Base::val();
      }
};
Run Code Online (Sandbox Code Playgroud)

如果我做Derived d1; 派生d2 = …

c++ inheritance

5
推荐指数
2
解决办法
5975
查看次数

标签 统计

c++ ×2

inheritance ×2