【发布时间】:2014-02-19 03:35:22
【问题描述】:
我的印象是这是不可能的,例如:
Calling the constructor of the base class after some other instructions in C++
但是下面的程序运行并产生了两行“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。
【问题讨论】:
-
所以根据下面的answers/cmets,答案是:应该准确理解“从子类D构造函数体调用基类的构造函数B”的含义。构造函数 B 不能以创建此子对象的父级部分的方式调用。谢谢大家!
-
也许可以。直接通过
placement new(不确定这样做是否可以),或者有时可以使用实用函数调用stackoverflow.com/questions/62434909/… 进行模拟
标签: c++ constructor base-class