【发布时间】:2021-11-11 17:38:24
【问题描述】:
我参加了一门 C++ 课程,其中我有以下代码 sn-p:
class Pet {
protected:
string name;
public:
Pet(string n)
{
name = n;
}
void run()
{
cout << name << ": I'm running" << endl;
}
};
class Dog : public Pet {
public:
Dog(string n) : Pet(n) {};
void make_sound()
{
cout << name << ": Woof! Woof!" << endl;
}
};
class Cat : public Pet {
public:
Cat(string n) : Pet(n) {};
void make_sound()
{
cout << name << ": Meow! Meow!" << endl;
}
};
int main()
{
Pet *a_pet1 = new Cat("Tom");
Pet *a_pet2 = new Dog("Spike");
a_pet1 -> run();
// 'a_pet1 -> make_sound();' is not allowed here!
a_pet2 -> run();
// 'a_pet2 -> make_sound();' is not allowed here!
}
我无法弄清楚为什么这是无效的。请为此建议合适的参考资料,以充分解释为什么会发生这种情况。
【问题讨论】:
-
我认为这与
virtual函数有关 -
有用的读物有助于避免您在不久的将来会遇到的常见问题What is an example of the Liskov Substitution Principle?
标签: c++ inheritance