Visual C++ 2010 で次のシナリオを想定してみましょう。
#include <iostream>
#include <conio.h>
using namespace std;
class Base
{
public:
int b;
void Display()
{
cout<<"Base: Non-virtual display."<<endl;
};
virtual void vDisplay()
{
cout<<"Base: Virtual display."<<endl;
};
};
class Derived : public Base
{
public:
int d;
void Display()
{
cout<<"Derived: Non-virtual display."<<endl;
};
virtual void vDisplay()
{
cout<<"Derived: Virtual display."<<endl;
};
};
int main()
{
Base ba;
Derived de;
ba.Display();
ba.vDisplay();
de.Display();
de.vDisplay();
_getch();
return 0;
};
理論的には、この小さなアプリケーションの出力は次のようになります。
- ベース: 非仮想ディスプレイ。
- ベース: 仮想ディスプレイ。
- ベース: 非仮想ディスプレイ。
- 派生: 仮想ディスプレイ。
Base クラスの Display メソッドは仮想メソッドではないため、Derived クラスはそれをオーバーライドできないはずです。右?
問題は、アプリケーションを実行すると、次のように出力されることです。
- ベース: 非仮想ディスプレイ。
- ベース: 仮想ディスプレイ。
- 派生: 非仮想ディスプレイ。
- 派生: 仮想ディスプレイ。
つまり、仮想メソッドの概念を理解していなかったか、Visual C++ で奇妙なことが起こったのです。
誰かが説明を手伝ってくれませんか?