【问题标题】:Is it valid to copy an inherited member in the derived class constructor?在派生类构造函数中复制继承的成员是否有效?
【发布时间】:2014-10-24 06:04:57
【问题描述】:

在下面的代码中,我在派生类中定义了一个显式的复制构造函数。我还在基类中编写了自己的复制构造函数。

Primer 说派生复制构造函数必须显式调用基类,并且继承的成员应该只由基类复制构造函数复制,但我在派生类复制构造函数中复制了继承的成员,它工作正常。这怎么可能?

另外,如何在派生类复制构造函数中显式调用基类复制构造函数? Primer 说的是 base(object),但我很困惑语法如何区分普通构造函数调用和复制构造函数调用。

提前致谢。

#include<stdafx.h>
#include<iostream>

using namespace std;

class A
{
public:
  int a;
  A()
  {
    a = 7;
  }

  A(int m): a(m)
  {
  }
};

class B : public A
{
public:
  int b;
  B()
  {
    b = 9;
  }

  B(int m, int n): A(m), b(n)
  {
  }

  B(B& x)
  {
    a = x.a;
    b = x.b;
  }

  void show()
  {
    cout << a << "\t" << b << endl;
  }
};

int main()
{
  B x;
  x = B(50, 100);
  B y(x);
  y.show();
  return 0;
}

【问题讨论】:

  • 请使用标点符号,不要使用制表符来缩进代码。
  • 您没有在A 中定义复制构造函数(有一个隐式生成的)。您不必从B 显式调用A 的复制构造函数。您的代码调用A 的复制构造函数,然后您覆盖这些值,这很好。

标签: c++ inheritance


【解决方案1】:

复制构造函数是指将另一个对象传递给构造函数:

class A() {
    private:
        int a;
    public:
        //this is an empty constructor (or default constructor)
        A() : a(0) {};
        //this is a constructor with parameters
        A(const int& anotherInt) : a(anotherInt) {};
        //this is a copy constructor
        A(const A& anotherObj) : a(anotherObj.a) {}; 
}

对于派生类

class B : public A {
    private:
         int b;
    public:
         //this is the default constructor
         B() : A(), b() {};
         //equivalent to this one
         B() {};
         //this is a constructor with parameters
         // note that A is initialized through the class A.
         B(const int& pa, const int& pb) : A(pa), b(pb) {}
         //for the copy constructor
         B(const B& ob) : A(ob), b(ob.b) {}        
}

【讨论】:

    【解决方案2】:

    其他人在这里是如何写的:

    How to call base class copy constructor from a derived class copy constructor?

    我会像这样编写复制构造函数,而不是 macmac 的编写方式:

    B(const B& x) : A(x) , b(x.b)
    {
    }
    

    要调用基 A 的复制构造函数,只需传递派生的 B 对象 A(B) 即可调用它,无需指定 B.a.

    编辑:macmac 以正确的方式编辑了他的答案,现在他的答案比我的好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 2015-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多