Settings | Sign in | Sign up

There are currently 2 posts.

【理解】虛函數的理解

Floor 1 巨大八爪鱼 4/8/16 18:40
【不用虛函數的情況】
在下面的程序中,聲明一個基類的指針變量,指向子類的實例,但是調用時卻只能調用父類的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.
Floor 2 巨大八爪鱼 4/8/16 18:42
此時,只需要把父類的Show函數聲明為虛函數,就能解決父類指針不能調用子類方法的問題:

運行結果:

Content converter:

Reply the post
Content:
User: You are currently anonymous.
Captcha:
Unclear? Try another one.
©2010-2025 Purasbar Ver3.0 [Mobile] [Desktop]
Except where otherwise noted, content on this site is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported license.