【不用虛函數的情況】 在下面的程序中,聲明一個基類的指針變量,指向子類的實例,但是調用時卻只能調用父類的Show函數: #include "stdafx.h" #include <iostream>
using namespace std;
class Person { public: char name[20]; void Show(void); };
void Person::Show(void) { cout << "I don't want to tell you my name." << endl; }
class Student : public Person { public: void Show(void); };
void Student::Show(void) { cout << "My name is " << name << "." << endl; }
int _tmain(int argc, _TCHAR* argv[]) { // 直接調用Show函數,正常 Student stu; strcpy_s(stu.name, "Tony"); stu.Show(); // 用子類的指針調用Show函數,正常 Student *pStu = &stu; pStu->Show();
// 用父類的指針調用Show函數,不正常! Person *pPerson = &stu; pPerson->Show();
return 0; } 【運行結果】 My name is Tony. My name is Tony. I don't want to tell you my name.
|