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; 
}
原文地址:https://www.cnblogs.com/my-love-is-python/p/13363982.html