我的印象是这是不可能的,例如:
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。
最佳答案
子类构造函数内部的调用不是调用基类构造函数,它是创建一个临时的、未命名的、类型为 Person 的新对象。它将在构造函数退出时被销毁。澄清一下,您的示例与执行此操作相同:
Child() { c = 1; Person tempPerson; }
除了在这种情况下,临时对象有一个名称。
如果您稍微修改一下您的示例,您就会明白我的意思:
class Person
{
public:
Person(int id):id(id) { std::cout << "Constructor Person " << id << std::endl; }
~Person(){ std::cout << "Destroying Person " << id << std::endl; }
int id;
};
class Child : public Person
{
public:
Child():Person(1) { c = 1; Person(2); }
int c;
};
int main() {
Child child;
Person(3);
return 0;
}
这会产生输出:
Constructor Person 1
Constructor Person 2
Destroying Person 2
Constructor Person 3
Destroying Person 3
Destroying Person 1
关于c++ - 从子类的构造函数体调用基类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21395395/