Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.

Join the forum, it's quick and easy

Evo. G Tech Team Forum
Welcome to Evo. G Tech Team Forum. We have moved to a new website : www.evogtechteam.com

Thanks you.

by Evo. G Tech Team Management.
Evo. G Tech Team Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.

C++和java 多态性的区别

Go down

C++和java 多态性的区别 Empty C++和java 多态性的区别

Post by too wei June 16th 2015, 23:06

多态性是面向对象程序设计的关键技术之一。利用多态性技术,可以调用同一个函数名的函数,实现完全不同的功能。


C++的多态性(polymorphism)
虚函数在C++中原本是用来实现动态联编的
但在构造函数中调用虚函数时,采用的不是动态联编而是静态联编,即父类A的构造函数中的init()调用的是自己的init()方法。

注意:以下注释了运行时的次序


class A {
protected:
 int num;
public:
 A() {                 //-----3
  num = 0;       //-----4
  init();             //-----5
  num = 1;      //-----8
 }
 
protected:
 virtual void init() {
  printf("i am A\n");         //-----6
  printf("%d\n",num);     //-----7
 }
};
 
class B:public A {
public:
 B() {               //-----2
  init();            //-----9
  num = 2;      //-----12
 }
protected:
 virtual void init() {
  printf("i am B\n");          //-----10
  printf("%d\n",num);      //-----11
 }
};
 
int main() {
 B* b = new B;      //-----1
 return 0;              //-----13
}


运行结果
i am A
0
i am B
1


java版本
java采用的是动态绑定技术。
构建子类B对象的时候,先调用父类A的构造函数,而A的构造函数中调用了init()方法,
此时对java来说还是在构建B对象的过程中,因此这个调用的init()方法不是父类A中的而是B中的

其中B类的init()被调用了2次

class A {
 protected int num;
 public A() {                  //--------3
  init();                          //--------4
  num = 1;                   //--------7
 }
 protected void init(){                   //没被调用到
  System.out.println("i am A");        
  System.out.println(num);
 }
}
 
class B extends A {
 public B(){               //--------2
  init();                      //--------8
  num = 2;                //--------11
 }
 protected void init(){
  System.out.println("i am B");              //--------5            //--------9
  System.out.println(num);                  //--------6            //--------10
 }
}
 
class Demo {
 public static void main(String[] args) {
  B b = new B();                                           //--------1
 }
}


运行结果
i am B
0
i am B
1

too wei
Sponsor
Sponsor

Posts : 31
Points : 66331
Reputation : 0
Join date : 2015-04-21
Age : 25
Location : Johor

Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum