C ++和Java中的虚拟机制

时间:2015-04-12 16:19:30

标签: java c++ oop vptr

我对C ++和Java中的虚拟机制有些困惑。以下程序的输出是不同的。我无法理解为什么?

在Java中:

class Base 
{ 
    Base()
    {
        show();
    }    
    public void show() 
    {
       System.out.println("Base::show() called");
    }
}

class Derived extends Base 
{
    Derived()
    {        
        show();        
    }
    public void show() 
    {
       System.out.println("Derived::show() called");
    }
}

public class Main 
{
    public static void main(String[] args) 
    {
        Base b = new Derived();
    }
}

输出是:

Derived::show() called
Derived::show() called

在C ++中,输出如下:

#include<bits/stdc++.h>
using namespace std;

class Base
{
    public:
    Base()
    {
        show();
    }
    virtual void show()
    {
       cout<<"Base::show() called"<<endl;
    }
};

class Derived : public Base
{
    public:
    Derived()
    {
        show();
    }
    void show()
    {
       cout<<"Derived::show() called"<<endl;
    }
};

int main()
{
    Base *b = new Derived;
}

是:

Base::show() called
Derived::show() called

有人可以解释一下吗?

0 个答案:

没有答案