思维导图
#include <iostream>
using namespace std;
class Animal
{
private:
string type;
public:
Animal(){}
Animal(string type):type(type){}
virtual void perfrom(){
cout << "我是" << type << endl;
}
};
class Cat:public Animal
{
private:
string name;
public:
Cat(){}
Cat(string type,string name):Animal(type),name(name){}
void perfrom()
{
cout << "猫在睡觉" << endl;
}
};
class Dog:public Animal
{
private:
string name;
public:
Dog(){}
Dog(string type,string name):Animal(type),name(name){}
void perfrom()
{
cout << "狗在奔跑" << endl;
}
};
int main()
{
Animal *ani;
Cat cat("猫","Tom");
ani = &cat;
ani->perfrom();
Dog dog("狗","大黄");
ani = &dog;
ani->perfrom();
return 0;
}
实现了父类定义一个虚函数,虚指针指向子类,使用子类函数的示例