为什么我们需要C+中的虚拟函数?我正在学习C+,我只是进入了虚拟函数。根据我在书中和网上所读到的,虚拟函数是基类中的函数,您可以在派生类中重写这些函数。但是在这本书的早些时候,当我学习基本继承时,我可以在派生类中重写基函数,而不需要使用virtual.我在这里错过了什么?我知道虚拟函数还有更多,而且它似乎很重要,所以我想弄清楚它到底是什么。我只是在网上找不到一个直截了当的答案。
3 回答
红颜莎娜
TA贡献1842条经验 获得超12个赞
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 filevoid 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*
func()
.
eat()
Animal
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."
慕森卡
TA贡献1806条经验 获得超8个赞
class Base{ public: void Method1 () { std::cout << "Base::Method1" << std::endl; } virtual void Method2 () { std::cout << "Base::Method2" << std::endl; }};class Derived : public Base{ public: void Method1 () { std::cout << "Derived::Method1" << std::endl; } void Method2 () { std::cout << "Derived::Method2" << std::endl; }};Base* obj = new Derived (); // Note - constructed as Derived, but pointer stored as Base*obj->Method1 (); // Prints "Base::Method1"obj->Method2 (); // Prints "Derived::Method2"
编辑
- 3 回答
- 0 关注
- 610 浏览
添加回答
举报
0/150
提交
取消