設置 | 登錄 | 註冊

作者共發了2篇帖子。

【理解】虛函數的理解

1樓 巨大八爪鱼 2016-4-8 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.
2樓 巨大八爪鱼 2016-4-8 18:42
此時,只需要把父類的Show函數聲明為虛函數,就能解決父類指針不能調用子類方法的問題:

運行結果:

內容轉換:

回覆帖子
內容:
用戶名: 您目前是匿名發表。
驗證碼:
看不清?換一張
©2010-2025 Purasbar Ver3.0 [手機版] [桌面版]
除非另有聲明,本站採用知識共享署名-相同方式共享 3.0 Unported許可協議進行許可。