且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Java和C ++之间的对象创建的主要区别是什么?

更新时间:2023-12-04 11:09:16

除了其他优秀的答案,有一件事非常重要,通常被忽略/被遗忘或误解我详细说明了下面的过程):

In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):


  • 在Java中,方法是虚拟的,即使从构造函数

  • 在C ++中,虚拟方法在从构造函数调用时不是虚拟的(可能导致误解) $ b

  • 让我们想象一个Base类,方法foo()。

  • 让我们想象一个继承自Base的Derived类,它覆盖了方法foo()

C ++和Java之间的区别是:

The difference between C++ and Java is:


    在Java中,从Base类构造函数调用foo Derived.foo()
  • 在C ++中,从Base类构造函数调用foo()将调用Base.foo()

每种语言的错误是不同的:

The "bugs" for each languages are different:


  • 在Java中,调用构造函数中的任何方法都可能导致微妙的错误,因为重写的虚拟方法可能会尝试访问在Derived类中声明/初始化的变量。


从概念上讲,构造函数的作用是使对象成为存在(这不是一个普通的专长)。在任何构造函数中,整个对象可能只是部分形成 - 你可以知道基类对象已经被初始化,但是你不知道哪些类继承自你。然而,动态绑定的方法调用到达前进或向外到继承层次结构中。它在派生类中调用一个方法。如果你在一个构造函数中这样做,你可以调用一个方法来处理尚未初始化的成员 - 一个确定的灾难处理方法。

Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches "forward" or "outward" into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.

Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml

Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml




  • 在C ++中,必须记住虚拟函数不会按预期工作,因为只有当前构造类的方法才会被调用。原因是为了避免访问数据成员或甚至尚不存在的方法。


  • 构造,虚函数永远不会进入派生类。相反,对象的行为就像是基类型。非正式地说,在基类构造期间,虚拟函数不是。

    During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.

    Scott Meyers, http://www.artima.com/cppsource/nevercall.html

    Scott Meyers, http://www.artima.com/cppsource/nevercall.html