#include <iostream> using namespace std; class A { public: A(string s) { cout<<"construct A:"<<s<<endl; a = s; } virtual void displayA() //=0 純虛擬不能實體化 { cout<<"dispalyA"<<endl; } protected: string a; }; class B:public A { public: B():A("before B"){cout<<"construct B"<<endl;} void displayA() //也是virtual 不需再加 { cout<<"dispalyB"<<endl; } void dispalyB() { cout<<a<<endl; } }; class C:public B { void displayA() //也是virtual 不需再加 { cout<<"dispalyC"<<endl; } }; int main() { cout << "Hello World" << endl; A ca("test"); //可實體化 ca.displayA(); A *pa; B cb; pa = &cb; pa->displayA(); //虛擬函式會往子class找有實作的 return 0;
結果: Hello World construct A:test dispalyA construct A:before B construct B dispalyB