从父类构造函数调用重写的方法 [英] Calling an overridden method from a parent class ctor

查看:30
本文介绍了从父类构造函数调用重写的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从父类的构造函数调用重写的方法,并注意到不同语言的行为不同.

I tried calling an overridden method from a constructor of a parent class and noticed different behavior across languages.

C++ - 回声 A.foo()

C++ - echoes A.foo()

class A{

public: 

    A(){foo();}

    virtual void foo(){cout<<"A.foo()";}
};

class B : public A{

public:

    B(){}

    void foo(){cout<<"B.foo()";}
};

int main(){

    B *b = new B(); 
}

Java - 回声 B.foo()

Java - echoes B.foo()

class A{

    public A(){foo();}

    public void foo(){System.out.println("A.foo()");}
}

class B extends A{  

    public void foo(){System.out.println("B.foo()");}
}

class Demo{

    public static void main(String args[]){
        B b = new B();
    }
}

C# - 回声 B.foo()

C# - echoes B.foo()

class A{

    public A(){foo();}

    public virtual void foo(){Console.WriteLine("A.foo()");}
}

class B : A{    

    public override void foo(){Console.WriteLine("B.foo()");}
}


class MainClass
{
    public static void Main (string[] args)
    {
        B b = new B();              
    }
}

我意识到在 C++ 中,对象是从层次结构中最顶层的父对象创建的,因此当构造函数调用重写的方法时,B 甚至不存在,因此它调用该方法的 A' 版本.但是,我不确定为什么我在 Java 和 C#(来自 C++)中得到不同的行为

I realize that in C++ objects are created from top-most parent going down the hierarchy, so when the constructor calls the overridden method, B does not even exist, so it calls the A' version of the method. However, I am not sure why I am getting different behavior in Java and C# (from C++)

推荐答案

在 C++ 中,正如您正确指出的,对象是 A 类型,直到 A 构造函数是完成的.对象实际上在其构造过程中改变了类型.这就是使用 A 类的 vtable 的原因,所以 A::foo() 被调用而不是 B::foo().

In C++, as you correctly noted, the object is of type A until the A constructor is finished. The object actually changes type during its construction. This is why the vtable of the A class is used, so A::foo() gets called instead of B::foo().

在 Java 和 C# 中,始终使用派生程度最高的类型的 vtable(或等效机制),甚至在构建基类期间也是如此.所以在这些语言中,B.foo() 被调用.

In Java and C#, the vtable (or equivalent mechanism) of the most-derived type is used throughout, even during construction of the base classes. So in these languages, B.foo() gets called.

注意,一般不建议从构造函数中调用虚方法.如果您不是很小心,虚拟方法可能会假设对象已完全构造,即使事实并非如此.在 Java 中,每个方法都是隐式虚拟的,您别无选择.

Note that it is generally not recommended to call a virtual method from the constructor. If you're not very careful, the virtual method might assume that the object is fully constructed, even though that is not the case. In Java, where every method is implicitly virtual, you have no choice.

这篇关于从父类构造函数调用重写的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆