从子类的构造函数体调用基类的构造函数

从子类的构造函数体调用基类的构造函数

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

问题描述

我的印象是,这是不可能的,例如:


但是下面的程序运行并产生两行Constructor Person:

I was under impression that it's impossible, see for example:Calling the constructor of the base class after some other instructions in C++
But the following program runs and produces two lines of "Constructor Person":

#include <iostream>

class Person
{
public:
    Person()
    {
        std::cout << "Constructor Person" << std::endl; }
    };

class Child : public Person
{
public:
    Child()
    {
        c = 1;
        Person();
    }
    int c;
};

int main()
{
    Child child;
    return 0;
}

第一个是隐式调用默认构造函数,很清楚。第二个 - 这是否意味着标题中描述的行动是合法的?我使用Visual C ++ 2010。

The first one is implicit call of the default constructor, that's clear. What about the 2nd one - does it mean that the action described in the title is legitimate? I use Visual C++ 2010.

推荐答案

以下是加速C ++的摘录:
派生对象构造方式:

1.为整个对象(基类成员以及派生类成员)分配空间;

2.调用基类构造函数来初始化base-对象的类部分;

3.按构造函数初始化程序的指示初始化派生类的成员;

4.执行派生类构造函数的主体(如果有) 。

The following is an excerpt from "Accelerated C++":"Derived objects are constructed by:
1. Allocating space for the entire object (base class members as well as derived class members);
2. Calling the base-class constructor to initialize the base-class part of the object;
3. Initializing the members of the derived class as directed by the constructor initializer;
4. Executing the body of the derived-class constructor, if any."

总结回答和注释:从子类的构造函数体中调用基类的构造函数是不可能的,因为#2必须在#4之前。
但是我们仍然可以在派生构造函数体中创建一个基础对象,从而调用一个基础构造函数。它将是一个与使用当前执行的派生构造函数构造的对象不同的对象。

Summarizing the answers and comments: Calling a constructor of the base class from a subclass' constructor body is impossible in the sense that #2 above must precede #4.But we still can create a base object in the derived constructor body thus calling a base constructor. It will be an object different from the object being constructed with the currently executed derived constructor.

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