任何人都可以在以下代码中向我解释构造函数的调用。
如果没有对象,而只有指向派生类的指针,则如何调用抽象类的构造函数。是否创建了它的实例来保存vtable?
#include <iostream>
using namespace std;
class pure_virtual {
public:
pure_virtual() {
cout << "Virtul class constructor called !" << endl;
}
virtual void show()=0;
};
class inherit: public pure_virtual {
public:
inherit() {
cout << "Derived class constructor called !" << endl;
}
void show() {
cout <<"stub";
}
};
main() {
pure_virtual *ptr;
inherit temp;
ptr = &temp;
ptr->show();
}
最佳答案
调用pure_virtual
的构造函数时,将调用inherit
类的构造函数。因此,执行inherit temp;
行时,将调用对象的构造函数,因为它是派生类。然后,首先调用基类的构造函数。
所以在您的情况下,输出将是
Virtul class constructor called !
Derived class constructor called !
并且因为
void show()
是虚拟的,所以调用了正确的函数,即inherit
类的函数。关于c++ - C++抽象类构造函数调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49715025/