• c++继承与多态


    继承

    #include <iostream.h>
    class A{
    public:
     static void add(){
        cout<<"dddd"<<endl;
     }
    };
    class Person{
    public:
     Person(int hand)
     {
      this->hand=hand;
     }
     int hand;
     void walk()
     {
      cout<<"person walk"<<endl;
     }
     void eat()
     {
      cout<<"person eat"<<endl;
     }
    };
    //如果public不写 能够实例化Chinese 不能调用Person的属性及方法 除非重写
    //proteced外部不能访问 子类中可以访问
    class Chinese : public Person{
    public:
     //调用子类的构造方法时会先调用父类的构造方法 父类没有默认的构造方法 可以指定调用就是下面的方式
     Chinese():Person(20)
     {
     }
     //::表示作用域标识符 前面的参数表示哪个类的哪个资源
     void eat()
     {
      //相当于java中的super.eat(); 当类中出现static标示的属性和方法可以使用::
      A::add();
      Person::eat();
      cout<<"Chinese eat"<<endl;
     }
    };

    void main(){
     Chinese c;
     c.eat();
    }

    多态

    #include <iostream.h>
    class Person{
    public:
     Person(int hand)
     {
      this->hand=hand;
     }
     int hand;
     void walk()
     {
      cout<<"person walk"<<endl;
     }
     virtual void eat()
     {
      cout<<"person eat"<<endl;
     }
     //表示一个空的虚方法 表示子类必须实现 这样表示该类 有空的虚方法就是抽象类了,不能实例化
     //相当于java中的 abstract void heart();

     virtual void heart()=0;
    };

    class Chinese : public Person{
    public:
     Chinese():Person(20)
     {
     }

     void eat()
     {
      cout<<"Chinese eat"<<endl;
     }
     void heart(){
      cout<<"Chinese heart"<<endl;
     }
    };
    void toeat(Person *person)
    {
     person->eat();
    }
    void toheart(Person *person)
    {
     person->heart();
    }

    void main()
    {
      Chinese chinese;
      Person *person=&chinese;
      //如果调用person->eat();调用的父类的eat() 如果在父类eat方法添加virtual 则调用子类的
      toeat(person);
      toheart(person);
    }

  • 相关阅读:
    为初次使用linux设置 root密码
    linux如何改为汉化环境
    Linux 标准目录结构
    常用linux terminal 命令
    jquery 获取及设置input各种类型的值
    使用$.getJSON实现跨域ajax请求
    react 异步取数据
    PHP 全局变量
    PHP保存本地日志文件
    全端开发——css(选择器)
  • 原文地址:https://www.cnblogs.com/liaomin416100569/p/9331642.html
Copyright © 2020-2023  润新知