子類別去繼承了父類別,父類別當然不能去呼叫到子類別的函數,而父類別本身可以透過虛擬函數的方法去呼叫到子類別的函數。
#include <iostream>
using namespace std;
class CA{
public :
virtual void Forward()=0;
virtual void Eat()=0;
void GoFor(){
Forward();
Eat();
}
};
class bird:public CA{
void Forward(){
cout<<"鳥在飛行,";
}
void Eat(){
cout<<"飛到水裡捕魚\n";
}
};
class dog:public CA{
void Forward(){
cout<<"狗在走路,";
}
void Eat(){
cout<<"跳上去吃到獵物\n";
}
};
void main()
{
bird b;
dog d;
b.GoFor();
d.GoFor();
system("pause");
}
參考文章:
http://blog.yam.com/swwuyam/article/12114648
http://puremonkey2010.blogspot.tw/2010/09/c-c-virtual.html
http://caterpillar.onlyfun.net/Gossip/CppGossip/VirtualFunction.html