前言:
参考:B站UP主鱼C_小甲鱼<C++快速入门>
代码调试平台:VS2017,调试成功。
问题描述:
问题描述:猫狗问题(虚方法)
代码实现:
//当在子类中对基类的方法进行覆盖时,使用new对变量进行声明时,调用覆盖的函数,
//为了执行更快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 << "正在玩耍!\n";
}
Cat::Cat(string theName) :Pet(theName)
{
}
void Cat::climb()
{
cout << name << "正在爬树。\n" << endl;
}
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->eat();
cat->sleep();
cat->play();
dog->eat();
dog->sleep();
dog->play();
delete cat;
delete dog;
return 0;
}