- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在学习 C++,并且刚刚接触虚函数。
据我所读(在书中和网上),虚函数是基类中的函数,您可以在派生类中覆盖这些函数。
但是在本书的前面,当学习基本继承时,我能够在不使用 virtual
的情况下覆盖派生类中的基函数。
那么我在这里缺少什么?我知道虚函数还有更多内容,而且它似乎很重要,所以我想弄清楚它到底是什么。我在网上找不到直接的答案。
最佳答案
这是我的理解方式,而不仅仅是 virtual
功能是,但为什么需要它们:
假设您有这两个类:
class Animal
{
public:
void eat() { std::cout << "I'm eating generic food."; }
};
class Cat : public Animal
{
public:
void eat() { std::cout << "I'm eating a rat."; }
};
在你的主函数中:
Animal *animal = new Animal;
Cat *cat = new Cat;
animal->eat(); // Outputs: "I'm eating generic food."
cat->eat(); // Outputs: "I'm eating a rat."
到目前为止还不错吧?动物吃普通食物,猫吃老鼠,所有这些都没有 virtual
。
现在让我们稍微改变一下,以便通过中间函数调用 eat()
(仅用于此示例的简单函数):
// This can go at the top of the main.cpp file
void func(Animal *xyz) { xyz->eat(); }
现在我们的主要功能是:
Animal *animal = new Animal;
Cat *cat = new Cat;
func(animal); // Outputs: "I'm eating generic food."
func(cat); // Outputs: "I'm eating generic food."
呃哦...我们将一只猫传递给 func()
,但它不会吃老鼠。您是否应该重载 func()
以便它需要一个 Cat*
?如果您必须从 Animal 派生更多动物,它们都需要自己的 func()
。
解决方案是使 Animal
类中的 eat()
成为虚函数:
class Animal
{
public:
virtual void eat() { std::cout << "I'm eating generic food."; }
};
class Cat : public Animal
{
public:
void eat() { std::cout << "I'm eating a rat."; }
};
主要内容:
func(animal); // Outputs: "I'm eating generic food."
func(cat); // Outputs: "I'm eating a rat."
完成。
关于c++ - 为什么我们需要 C++ 中的虚函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26436700/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!