考虑以下示例代码:
#include <iostream>
using namespace std;
class base
{
public:
base()
{
bar(); //Line1
this->bar(); //Line2
base *bptr = this;
bptr->bar(); //Line3
((base*)(this))->bar(); //Line4
}
virtual void bar() = 0;
};
class derived: base
{
public:
void bar()
{
cout << "vfunc in derived class\n";
}
};
int main()
{
derived d;
}
上面的代码在基类中具有纯虚函数bar()
,在派生类中被覆盖。纯虚函数bar()
在基类中没有定义。
现在关注Line1
,Line2
和。Line3
Line4
我了解:Line1
给出编译错误,因为无法从 ctor 调用纯虚函数。
问题:
为什么
Line2
和上面声明中提到的相同原因不Line4
给出?呼入和最终只会引起。compilation error
I understand
Line2
Line4
linker-error
为什么
Line3
既不给出编译错误也不给出链接器错误,而run-time exception
只给出?
通过构造函数调用纯虚函数时UB的真实例子: