class CoffeeBean{
public:
virtual void ShowCoffeeName(){};//基类的虚函数记得定义,不然会报错error LNK2001
virtual void ShowPrice(){};
public:
std::string m_name;
int m_price;
};
class Coffee:public CoffeeBean{
public:
Coffee(std::string name,int price)
{
m_name=name;
m_price=price;
};
virtual void ShowCoffeeName() override
{
std::cout << "CoffeeBean name:" << m_name << std::endl;
}
virtual void ShowPrice() override
{
std::cout << "CoffeeBean name:" << m_price << std::endl;
}
};
当子类继承基类时,需要基类的虚函数声明并且定义不然会报错。注意观察下面两种形式
虚方法声明形式:
virtual void ShowCoffeeName();
虚函数声明并定义形式:
virtual void ShowCoffeeName(){};