89 lines
1.6 KiB
C++
89 lines
1.6 KiB
C++
#include <iostream>
|
|
#include <cstring>
|
|
#include <cstdlib>
|
|
|
|
using namespace std;
|
|
|
|
class Animal
|
|
{
|
|
protected:
|
|
string name;
|
|
float price;
|
|
|
|
public:
|
|
Animal(const string &name, float price)
|
|
{
|
|
this->name = name;
|
|
this->price = price;
|
|
}
|
|
virtual void buy(); // 类内声明的虚函数
|
|
};
|
|
|
|
// 类外实现类中的虚函数
|
|
void Animal::buy()
|
|
{
|
|
cout << "小宠物 " << name << " 卖了 " << price << endl;
|
|
}
|
|
|
|
class Dog : public Animal
|
|
{
|
|
private:
|
|
int age;
|
|
|
|
public:
|
|
Dog(string name, float price, int age) : Animal(name, price), age(age)
|
|
{
|
|
}
|
|
virtual void buy() // 重写父类的虚函数
|
|
{
|
|
cout << age << " 岁小狗 " << name << " 卖了 " << price << endl;
|
|
}
|
|
void eat() // 扩展的新功能
|
|
{
|
|
cout << name << " 喝酒" << endl;
|
|
}
|
|
};
|
|
|
|
class Cat : public Animal
|
|
{
|
|
private:
|
|
int age;
|
|
|
|
public:
|
|
Cat(string name, float price) : Animal(name, price)
|
|
{
|
|
}
|
|
virtual void buy() // 重写父类的虚函数
|
|
{
|
|
cout << "小猫 " << name << " 卖了 " << price << endl;
|
|
}
|
|
void eat() // 扩展的新功能
|
|
{
|
|
cout << name << " 吃鱼" << endl;
|
|
}
|
|
};
|
|
|
|
class AnimalShop
|
|
{
|
|
public:
|
|
// 多态应用之一
|
|
void buy(Animal *animal)
|
|
{
|
|
cout << "-----动物之家正在出售小宠物-----" << endl;
|
|
animal->buy();
|
|
cout << "-----出售结束-----" << endl;
|
|
|
|
delete animal; // 释放堆区空间
|
|
}
|
|
};
|
|
|
|
int main()
|
|
{
|
|
AnimalShop shop;
|
|
Dog dog("旺财", 1000, 3);
|
|
// 多态的应用
|
|
shop.buy(&dog);
|
|
shop.buy(new Cat("小花", 500));
|
|
return 0;
|
|
}
|