当我从基本构造函数调用虚函数时,编译器不会给出任何错误。但是当我从基类构造函数调用纯虚函数时,它会出现编译错误。
考虑下面的示例程序:
#include <iostream>
using namespace std;
class base
{
public:
void virtual virtualfunc() = 0;
//void virtual virtualfunc();
base()
{
virtualfunc();
}
};
void base::virtualfunc()
{
cout << " pvf in base class\n";
}
class derived : public base
{
public:
void virtualfunc()
{
cout << "vf in derived class\n";
}
};
int main()
{
derived d;
base *bptr = &d;
bptr->virtualfunc();
return 0;
}
这里可以看出纯虚函数是有定义的。我希望在执行 bptr->virtualfunc()
时调用基类中定义的纯虚函数。相反,它给出了编译错误:
error: abstract virtual `virtual void base::virtualfunc()' called from constructor
这是什么原因?
最佳答案
不要从构造函数中调用纯虚函数,因为它会导致未定义的行为。
C++03 10.4/6 状态
"Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined."
你得到一个编译错误,因为你没有在 Base 类中定义纯虚函数 virtualfunc()
。为了能够调用它,它必须有一个 body 。
无论如何,应该避免在构造函数中调用纯虚函数,因为这样做是未定义的行为。
关于c++ - 从构造函数调用虚函数和纯虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8642363/