未调用基本复制构造函数 [英] Base Copy constructor not called

查看:172
本文介绍了未调用基本复制构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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();
      }
};

如果我做
派生d1;
派生d2 = d1;
调用base的复制构造函数并调用derived的默认复制构造函数。

If i do Derived d1; Derived d2 = d1; The copy constructor of base is called and default copy constructor of derived is called.

但是如果我从derived的复制构造函数中删除注释,则基本复制构造函数是不叫。这有什么具体原因吗?
提前致谢。

But if i remove the comments from derived's copy constructor the base copy constructor is not called. Is there any specific reason for this? Thanks in advance.

推荐答案

如果你想阅读实际规则,你应该参考C ++标准12.8 / 8:

If you want to read actual rule you should refer to C++ Standard 12.8/8:


类X的隐式定义的复制构造函数执行其子对象的成员副本。
复制顺序与用户定义的构造中的基础和成员的初始化顺序相同(见12.6.2)。每个子对象都以适合其类型的方式复制:

The implicitly-defined copy constructor for class X performs a memberwise copy of its subobjects. The order of copying is the same as the order of initialization of bases and members in a user-defined construc- tor (see 12.6.2). Each subobject is copied in the manner appropriate to its type:


  • 如果子对象是类类型,则使用该类的复制构造函数;

  • 如果子对象是一个数组,则每个元素都以适合于元素类型的方式复制;

  • 如果子对象是标量的类型,使用内置赋值运算符。

当你明确定义复制构造函数时,你应该明确地调用基类的复制c-tor。

When you define copy constructor explicitly you should call copy c-tor of base class explicitly.

这篇关于未调用基本复制构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆