本文介绍了面向对象程序设计,继承,复制构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a base class Person and I publicly inherit a class Teacher from base class Person. Now in the main function I write something like this

// 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类的默认副本构造函数将首先调用基类的副本构造函数.

Now I have not written the copy constructor for both the classes, off course the default copy constructors will be called. The Person class’s default copy constructor will first call the base class’s copy constructor.

现在的问题是假设我只为基类编写副本构造函数,发生的是,派生类的默认副本构造函数将调用我的书面副本构造函数.
现在假设我为两个类都编写了复制构造函数.现在派生类(即教师)的副本构造函数将调用基类的默认构造函数,而不是副本构造函数为什么?
是否只有派生类的默认副本构造函数才能自动调用基类的副本构造函数?

Now the problem is suppose I write the copy constructor for the base class only, what happens is, the default copy constructor of the derived class will call my written copy constructor.
Now suppose I write the copy constructor for both the classes . now the copy constructor of the derived class (i.e Teacher) will call the default constructor of the base class but not the copy constructor why?
Is only default copy constructor of the derived class can call the copy constructor of the base class automatically?

推荐答案

您必须显式调用基本副本构造函数:

You have to call the base copy constructor explicitly:

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

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

Otherwise Person's default constructor will be called.


我似乎还没有完全理解这个问题,所以我只说所有我认为相关的内容,希望对OP有所帮助.


I seem to not fully understand the question so I'll just say everything I think is relevant and hopefully this will help the OP.

所有用户定义的构造函数默认情况下都调用其基础的默认构造函数(除非它们显式调用其他构造函数),无论该基础的默认构造函数是用户定义的还是编译器生成的,都没有关系.

All user defined constructors call their base's default constructor by default (unless they explicitly call a different constructor), it doesn't matter if the base's default constructor is user defined or compiler generated.

由编译器生成副本构造函数时,它将调用基类的副本构造函数.

When a copy constructor is generated by the compiler it will call the base class's copy constructor.

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

Compiler defined constructors are not special, they can be called explicitly:

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_)
    {
    }
};

有关更多详细信息,请参见维基百科文章.

For more details see this Wikipedia article.

这篇关于面向对象程序设计,继承,复制构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 15:50