多型的作用__呼叫父類和子類函式實現分層
阿新 • • 發佈:2020-08-20
#include<iostream>
using namespace std;
class Father
{
public:
void testFather()
{
cout << "testFather1" << endl;
VirtualFunction();//這裡的函式會呼叫子類的虛擬函式嗎???會呼叫,如果子類沒有實現這個虛擬函式,會呼叫父類的虛擬函式不報錯
}
virtual void VirtualFunction()
{
cout << "Father:hellowold\n " << endl;
}
};
class Son :public Father
{
public:
void testson()
{
cout << "testson" << endl;
}
virtual void VirtualFunction()
{
cout << "Son:hellowold\n" << endl;
}
};
int main(void)
{
Son* myson = new Son;
myson->testFather();
cout << "helloworld\n" << endl;
getchar();
return 0;
}
/*多型實現時候,當父類特有函式中,呼叫和子類同名的虛擬函式時,會呼叫子類的虛擬函式。
*總結::先呼叫父類的方法去執行固定的操作,如進行系統基類的設定,分配記憶體區域供子函式使用等,然後呼叫到子函式去進行特定業務的處理。
*/