class Base
{
virtual void method()
{ cout << "Run by the base."; };
public:
Base() { method(); };
};
class Derived: public Base
{
void method()
{ cout << "Run by the derived."; };
};
void main()
{
Derived();
}
输出:
Run by the base.
如何在不创建派生构造函数的情况下运行派生方法?
答案 0 :(得分:3)
答案 1 :(得分:2)
你不能因为对象的“派生”部分尚未构造,所以从中调用成员函数将是未定义的行为。
答案 2 :(得分:1)
如果不添加额外代码,则无法执行此操作。
实现此目的的常用方法是使用私有构造函数和create
函数,该函数首先调用构造函数(通过new
),然后使用新创建的第二个finish_init
方法宾语。这确实可以防止您在堆栈上创建对象的实例。