一:C++ 虚函数定义
在其他语言中实现多态的基础就是基类中存在抽象方法,然后子类去实现抽象方法从而实现了多态,但是在C++中实现多态遇到了一些问题,首先咱们先看一下虚函数的定义:
/*
抽象基类
*/
class Creature {
private:
string _skill;
public:
string type;
string name;
int age;
Creature() {
cout << "a default creature is created.." << name << age << type << endl;
};
Creature(const string& t,const string& n,const int a): type(t),name(n),age(a) {
cout << "creature was created" << endl;
cout << "type of " << type << " creature was created and it's name is " << name << " age is " << age << endl;
}
~Creature() {
cout << name << " creatrue was deleted" << endl;
}
/* 子类必须继承 纯虚函数不能指向子类对象 */
virtual void eat() = 0;
};
上面的的存虚函数,子类必须实现这个方法
/* 子类必须继承 纯虚函数不能指向子类对象 */
virtual void eat() = 0;
子类中实现: