zoukankan      html  css  js  c++  java
  • C++基础-虚方法

    当在子类中对基类的方法进行覆盖时,使用Pet *cat = new Cat("加菲") 进行变量声明时,调用覆盖的函数,为了执行更快C++优先读取基类的方法,因此在基类声明时,需要将其方法声明为虚方法

    #include <iostream>
    #include <string>
    
    using namespace std;
    class Pet
    {
    public:
        Pet(string theName);
    
        void eat();
        void sleep();
        virtual void play(); //被子类覆盖的方法
    
    protected:
        string name;
    };
    
    class Cat : public Pet
    {
    public:
        Cat(string theName);
    
        void climb();
        void play();
    };
    
    class Dog :public Pet
    {
    public:
        Dog(string theName);
    
        void bark();
        void play();
    
    };
    
    Pet::Pet(string theName){
        name = theName;
    }
    
    void Pet::eat() {
        cout << name << "正在吃东西
    ";
    }
    
    void Pet::sleep() {
        cout << name << "正在睡觉
    ";
    }
    
    void Pet::play() {
        cout << name << "正在玩儿
    ";
    }
    
    Cat::Cat(string theName) : Pet(theName){
    
    }
    
    void Cat::climb() {
        cout << name << "正在爬树
    ";
    }
    
    void Cat::play() {
        Pet::play();
        cout << name << "玩毛线球
    ";
    }
    
    Dog::Dog(string theName) : Pet(theName){
    
    }
    
    void Dog::bark() {
        cout << name << "旺 旺
    ";
    }
    
    void Dog::play() {
        Pet::play();
        cout << name << "正在追赶该死的猫
    ";
    }
    
    int main() {
    
        Pet *cat = new Cat("加菲");
        Pet *dog = new Dog("欧迪");
    
        cat->sleep();
        cat->eat();
        cat->play();
    
        dog->sleep();
        dog->eat();
        dog->play();
    
        delete cat;
        delete dog;
    
        return 0; 
    }
  • 相关阅读:
    高级数据类型--字典(dict)
    一些JS常用的方法
    怎样提高WebService的性能
    Microsoft Enterprise Library 5.0 系列(三)
    Microsoft Enterprise Library 5.0 系列(四)
    Expression Blend学习二UI布局
    Expression Blend学习四控件
    Expression Blend学习5控件
    Expression Blend学习动画基础
    WPF三维图形
  • 原文地址:https://www.cnblogs.com/my-love-is-python/p/13363982.html
Copyright © 2011-2022 走看看