Mat*_*nes 5 c++ java inheritance
我想知道为什么这条JAVA代码产生的输出与C++中的相同代码不同.
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
A(){
this->Foo();
}
virtual void Foo()
{
cout << "A::Foo()" << endl;
}
};
class B : public A
{
public:
B()
{
this->Foo();
}
virtual void Foo()
{
cout << "B::Foo()" << endl;
}
};
int main(int, char**)
{
B objB;
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这会产生输出:
A::Foo()
B::Foo()
Run Code Online (Sandbox Code Playgroud)
JAVA代码是:
public class Testa {
public Testa()
{
this.Foo();
}
public static void main(String[] args)
{
Testb b = new Testb();
}
void Foo()
{
System.out.println("A");
}
}
class Testb extends Testa {
public Testb()
{
this.Foo();
}
@Override
void Foo()
{
System.out.println("B");
}
}
Run Code Online (Sandbox Code Playgroud)
此代码仅生成
B
B
Run Code Online (Sandbox Code Playgroud)
在这种情况下,为什么这个输出不同?
不同之处在于在构造过程中处理多态性.在Java中,对象的动态类型是派生类的动态类型,允许您甚至在构造函数有机会设置成员变量之前调用成员函数.这是不好的.
C++有不同的方法:在构造函数运行时,对象的类型被认为是构造函数所属的类之一.根据该假设,对成员函数的所有调用都是静态解析的.因此,的构造函数A调用A::foo()中,而构造函数B调用B::foo().