- 虚函数
通过基类的指针调用该成员函数时,将根据指针指向的对象类型确定调用的函数,而非指针的类型
是C++ 多态的一种体现,属于 函数的重写, 而非 重载。 要求函数的名称,参数完全一致。
class Animal
{
public:
void eat() {
std::cout << "I'm eating animal food."
}
};
class Dog : public Animal
{
public:
void eat() {
std::cout << "I'm eating a bone."
}
};
Animal *animal = new Animal;
Dog *dog = new Dog;
Animal *animal2 = new Dog;
animal ->eat();
cat ->eat();
animal2 ->eat();
输出:
I’m eating animal food.
I’m eating a bone.
I’m eating animal food.
但是,如果把基类中函数设置成 virtual 虚函数,则结果就不同:
class Animal
{
public:
virtual void eat() {
std::cout << "I'm eating animal food."
}
};
class Dog : public Animal
{
public:
void eat() {
std::cout << "I'm eating a bone."
}
};
Animal *animal = new Animal;
Dog *dog = new Dog;
Animal *animal2 = new Dog;
animal ->eat();
cat ->eat();
animal2 ->eat();
输出:
I’m eating animal food.
I’m eating a bone.
I’m eating animal bone.
- 虚继承
class Biology
{
public: