面向对象的编程,继承,复制构造函数

时间:2010-01-17 20:19:39

标签: c++ oop

假设我有一个基类Person,并且我从基类Teacher公开继承了一个类Person。 现在在main函数中我写了这样的东西

// name will be passed to the base class constructor and 17
// is for derived class constructor.
Teacher object(“name”,17) ;
Teacher object1=object; //call to copy constructor

现在我还没有为这两个类编写复制构造函数,当然会调用默认的复制构造函数。 Person类的默认复制构造函数将首先调用基类的复制构造函数。

现在问题是假设我只为基类编写复制构造函数,会发生什么,派生类的默认复制构造函数将调用我的书写复制构造函数。
现在假设我为这两个类编写了复制构造函数。现在派生类(即Teacher)的复制构造函数将调用基类的默认构造函数而不是复制构造函数为什么?
派生类的默认复制构造函数是否可以自动调用基类的复制构造函数?

3 个答案:

答案 0 :(得分:8)

您必须明确调用基本副本构造函数:

Teacher(const Teacher& other) 
    : Person(other) // <--- call Person's copy constructor.
    , num_(other.num_)
{
}

否则将调用Person的默认构造函数。

<小时/> 我似乎并不完全理解这个问题所以我只会说出我认为相关的一切,希望这对OP有所帮助。

默认情况下,所有用户定义的构造函数都调用其基类的默认构造函数(除非它们显式调用不同的构造函数),如果基类的默认构造函数是用户定义的或编译器生成的,则无关紧要。

当编译器生成复制构造函数时,它将调用基类的复制构造函数。

编译器定义的构造函数不是特殊的,可以显式调用它们:

class Base {
    int num_
public:
    Base(int n) : num_(n) { }
    // copy constructor defined by compiler
};

class Derived : public Base {
    float flt_;
public:
    Derived(float f, int n) : Base(n), flt_(f) { }
    // Copy constructor
    Derived(const Derived& other)
        : Base(other) // OK to explicitly call compiler generated copy constructor
        , flt_(other.flt_)
    {
    }
};

有关详细信息,请参阅此Wikipedia article

答案 1 :(得分:1)

如果未指定复制构造函数,则编译器会自动生成一个复制构造函数。生成此构造函数的方式是调用基类的复制构造函数。

如果您自己实现了复制构造函数,还要指定应该使用哪个基类构造函数(请参阅Motti的答案)。如果你没有指定任何东西,则使用默认构造函数(这就是它被称为“默认构造函数”的原因:在未明确指定构造函数时使用它。)

因此,编译器会自动生成一个合理的复制构造函数,但是如果你想要一些特殊的东西,那么就不会有更多的魔法,你必须自己指定构造函数的确切外观。

答案 2 :(得分:1)

class Base {
    int num_
public:
    Base(int n) : num_(n) { }
    // copy constructor defined by compiler
};

class Derived : public Base {
    float flt_;
public:
    Derived(float f, int n) : Base(n), flt_(f) { }
    // Copy constructor
    Derived(const Derived& other)
        : Base(other) // OK to explicitly call compiler generated copy constructor
        , flt_(other.flt_)
    {
    }
};
相关问题