C++的子類與孫子類都實現了虛函數時,孫子類的實現會覆蓋掉子類的實現。
繼承的最主要的應用就是把不同的類放到一個數組中,然后遍歷調用同名函數。
實例如下:
#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;
class Parent{
protected:
string pname;
public:
Parent(string name){
pname=name;
}
virtual void printName(){};
};
class Child: public Parent{
protected:
string cname;
public:
Child(string name):Parent(name){
cname=name;
}
virtual void printName(){
cout<<"This is child, cname is "<<cname<<", pname is "<<pname<<endl;
}
};
class GrandChild: public Child{
private:
string gname;
public:
GrandChild(string name):Child(name){
gname=name;
}
virtual void printName(){
cout<<"This is grandchild, gname is "<<gname<<", cname is "<<cname<<", pname is "<<pname<<endl;
}
};
int main(){
string name="C";
Child child(name);
name="GC";
GrandChild gchild(name);
vector<Parent*> mlist;
mlist.push_back(dynamic_cast<Parent*>(&child));
mlist.push_back(dynamic_cast<Parent*>(&gchild));
for(int i=0;i<mlist.size();++i){
mlist[i]->printName();
}
}
注意子類與孫子類的printName函數前的virtual可加可不加,都可以正確運行……不知道哪個才是正確寫法= =
