标签:rtu 使用 ace int style ret 执行 dog protected
当在子类中对基类的方法进行覆盖时,使用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 << "正在吃东西\n"; } void Pet::sleep() { cout << name << "正在睡觉\n"; } void Pet::play() { cout << name << "正在玩儿\n"; } Cat::Cat(string theName) : Pet(theName){ } void Cat::climb() { cout << name << "正在爬树\n"; } void Cat::play() { Pet::play(); cout << name << "玩毛线球\n"; } Dog::Dog(string theName) : Pet(theName){ } void Dog::bark() { cout << name << "旺 旺\n"; } void Dog::play() { Pet::play(); cout << name << "正在追赶该死的猫\n"; } 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; }
标签:rtu 使用 ace int style ret 执行 dog protected
原文地址:https://www.cnblogs.com/my-love-is-python/p/13363982.html