【问题标题】:Java/C++ Object creation orderJava/C++ 对象创建顺序
【发布时间】:2014-03-13 09:51:12
【问题描述】:

请看下面这段代码:

class Parent {
    Parent() {
        printFunction();
    }

    public void printFunction() {
        System.out.println("Parent Print");
    }

    class ParentInner {
       ParentInner() {
          InnerPrint();
       }

       void InnerPrint() {
          System.out.println("Parent Inner print");
       }
    }
}

class Child extends Parent {
    ChildInner ci;
    Child() {
        super();
        ci = new ChildInner();
    }

    @Override
    public void printFunction() {
        System.out.println("Child Print");
    }

    class ChildInner extends ParentInner {
       ChildInner() {
          super();
       }

       @Override
       void InnerPrint() {
          System.out.println("Child Inner print");
       }
    }

    public static void main(String[] args) {
        Child c = new Child();
    }
}

Java 编译器(eclipse 和 linux)的这段代码的输出是:

Child print
Child Inner print

这个,在 C++ (gcc) 中

#include <iostream>
#include <new>
using namespace std;

class Parent {
    public:
    Parent() {
        printFunction();
    }

    virtual void printFunction() {
        cout << "Parent print\n";
    }

    class ParentInner {
       public:
       ParentInner() {
          InnerPrint();
       }

       virtual void InnerPrint() {
          cout << "Parent Inner print\n";
       }
    };
};

class Child : public Parent {
    public:
    Child():Parent() {
        ci = new ChildInner();
    }

    void printFunction() {
        cout << "Child print\n";
    }

    class ChildInner : public ParentInner {
       public:
       ChildInner():ParentInner() {
       }

       void InnerPrint() {
          cout << "Child Inner print\n";
       }
    };

    ChildInner *ci;
};

int main(int argc, char* argv[]) {
   Child *c = new Child();
   return 0;
}

打印:

Parent print
Parent Inner print

怎么说?我认为首先创建基类,然后子类 gcc 是合乎逻辑的。 Java 中发生了什么?

【问题讨论】:

  • 你的 C++ 代码是什么?
  • 不看C++代码什么都说不出来。
  • Java部分很容易理解:Child覆盖了所有Parent方法,所以去掉了所有Parent行为
  • 在 C++ 中也是如此。那为什么顺序会不同呢?

标签: java c++ object


【解决方案1】:

正如你所怀疑的那样。当您从 Child 构造函数初始值设定项列表中调用 Parent 构造函数时,Child 对象尚未完全创建。所以在某种程度上还没有Child 对象,只有Parent 对象。

【讨论】:

  • 这就是我的想法——这在 C++ 中是有意义的。在 Java 中,它以相反的方式打印 - 所有子打印。
  • @GreenBee 虽然 C++ 和 Java 有许多相似之处,但它们大多是语法上的。 C++ 和 Java 仍然是非常不同的语言,其中的区别在于成员函数的覆盖和绑定。
  • 没错,我也推断出:) 是否有任何资源可以理解两者中的对象创建?这看起来莫名其妙。我找不到正确解释上述流程的资源 - 主要是差异。
猜你喜欢
  • 2016-06-02
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 1970-01-01
相关资源
最近更新 更多