#include <iostream>
using namespace std;
/*
* base class
*/
class A
{
public:
A()
{
this->init();
}
virtual void init()
{
cout << " A";
}
// in public, so class B can call it.
void testit()
{
this->init();
}
};
/*
* child class
*/
class B : public A
{
public:
B()
{
this->init();
}
virtual void init()
{
// here get segmentation fault.
// but if call A::init() then it is ok.
A::testit();
// if call A::init(); then it working.
cout << "B" ;
}
};
int main()
{
B b;
A * a = &b;
// here B virtual function will be called.
a->init();
return 0;
}
基本上,這是一個虛擬功能測試。但是我發現,當子類調用基類函數內部的自身虛函數時,會得到運行時分段錯誤。爲什麼?爲什麼虛擬函數給定分段故障
這裏的時候,運行時間得到它分割的錯,因爲在A ::調用testIt() 但爲什麼呢?
爲什麼子實例調用基函數會出錯?
需要注意的是,當對象的'init'方法在'A'的構造函數或析構函數內被調用時'B :: init'不會被調用。這是因爲'this'指針在這些階段沒有指向類「B」的對象,而是指向類「A」的對象,所以對'init'的任何調用都會調用'A :: init'代替。多態性不派遣構造函數和析構函數中的派生類的虛方法調用,因爲派生類不存在於這些階段。 –