原文出自:http://blog.csdn.net/hihui/article/details/8604779
- #include <stdio.h>
- class Base
- {
- public:
- int i;
- Base()
- {
- i = 99;
- amethod();
- }
- virtual void amethod()
- {
- printf("Base.amethod()\n");
- }
- };
- class Derived : public Base
- {
- public:
- int i;
- Derived() {
- i = -1;
- }
- virtual void amethod()
- {
- printf("Derived.amethod()\n");
- }
- };
- int main(int argc, char *argv[])
- {
- Base *b = new Derived();
- printf("%d\n",b->i);
- b->amethod();
- }
其输出结果为:
Base.amethod()
99
Derived.amethod()
同样的java代码
[java] view plaincopy
- class Base
- {
- int i = 99;
- public void amethod()
- {
- System.out.println("Base.amethod()");
- }
- Base()
- {
- amethod();
- }
- }
- class Derived extends Base
- {
- int i = -1;
- public void amethod()
- {
- System.out.println("Derived.amethod()");
- }
- public static void main(String argv[])
- {
- Base b = new Derived();
- System.out.println(b.i);
- b.amethod();
- }
- }
其输出结果为
Derived.amethod()
99
Derived.amethod()
差异体现在第一行输出;
这行是在Derived的构造函数中输出的,Derived本身没有构造函数,它只调用父类的构造函数,即Base的amethod();
对于C++代码,执行的是Base::amethod();
对于Java代码,执行的是Derived::amthod();
为什么呢,在C++中调用基类的amethod时,此时子类还没有准备好,故执行的是基类的amethod.
时间: 2024-10-18 22:21:16