参考博客:点我

  

  要点:Java中的普通函数默认为虚函数,因此动态绑定的行为是默认的,而C++必须将方法声明为虚函数(virtual关键字),执行时才会进行动态绑定,详细区别可参考代码以及注释。

  代码大致:实现父类 Animal类,包含数据成员 姓名和年龄,以及实现eat方法和informa方法,子类Dog类继承于Animal,并实现方法的覆盖。Java和C++中都没有显示声明为虚函数,但观察输出结果可知,Java中实现了动态绑定,而C++没有,只有将相应函数加上virtual关键字,才实现动态绑定。这就是Java和C++处理的不同之处

 

C++代码:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

class Animal{
public:
    char name[20];
    int age;

    Animal(){
        age = 0;
        name[0] = 0;
    }

    Animal(char* nName, char nAge){
        strcpy(name, nName);
        age = nAge;
    }

    void eat(){
        printf("Animal can eat!\n");
    }

    //可在此加上virtual关键字观察输出区别
    void information(){
        printf("%s is a Animal, it's %d years old!\n", name, age);
    }
};

class Dog :public Animal{

public:
    Dog() :Animal(){}
    Dog(char* nName, int nAge) :Animal(nName, nAge){}

    void eat(){
        printf("Dog can eat!\n");
    }

    void information(){
        printf("%s is a Dog, it's %d years old!\n", name, age);
    }
};


int main()
{
    Animal* A = new Animal("A", 10);
    Animal* B = new Dog("B", 20);

    A->information();
    //C++必须显示声明为虚函数才能实现多态 否则只是调用父类的方法而不会调用子类的
    B->information(); 


    return 0;
}
View Code

相关文章:

  • 2021-09-08
  • 2022-12-23
  • 2021-09-19
  • 2021-09-03
  • 2021-11-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-09
  • 2021-08-20
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案