【不用虚函数的情况】 在下面的程序中,声明一个基类的指针变量,指向子类的实例,但是调用时却只能调用父类的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.
|