C++基類的繼承和多態
虛函數:
子類的虛函數會覆蓋基類同名的函數。
非虛函數:
指針聲明是什么類型,就只能訪問該類所擁有的函數。。
要特別注意指針聲明成什么類型。。。。和它 new 的類型無關。。。無關。。
class Base { public: Base(){}; ~Base(){}; public: virtual void printHello() { cout << "Base: Base say hello"<<endl; } void printName() { cout << "Base: I am Base" << endl; } void printDate() { cout << "Base: Base 6666" << endl; } }; class Drive : public Base { public: Drive(){}; ~Drive(){}; public: virtual void printHello() { cout << "Drive: Drive say hello" << endl; } void printName() { cout << "Drive: I am Drive" << endl; } void printAge() { cout << "Drive: Age 29" << endl; } }; int main(int argc, char* argv[]) { //Test1(); //Test2(); //Test3(); //Test4(); //Test5(); //Test6(); //Test7(); Base* objB1 = new Drive(); objB1->printHello(); objB1->printName(); objB1->printDate(); // objB1->printAge(); //編譯器會報錯 ///輸出結果如下: // Drive: Drive say hello // Base : I am Base // Base : Base 6666 cout << endl; system("pause"); return 0; }