我对 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
有人可以解释一下吗?