Java / C ++对象创建顺序

时间:2014-03-13 09:51:12

标签: java c++ object

请查看以下代码:

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

说什么?我认为基类首先被创建,然后child-gcc是合乎逻辑的。什么是Java?

1 个答案:

答案 0 :(得分:0)

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