為什么我們需要C+中的虛擬函數?我正在學習C+,我只是進入了虛擬函數。根據我在書中和網上所讀到的,虛擬函數是基類中的函數,您可以在派生類中重寫這些函數。但是在這本書的早些時候,當我學習基本繼承時,我可以在派生類中重寫基函數,而不需要使用virtual.我在這里錯過了什么?我知道虛擬函數還有更多,而且它似乎很重要,所以我想弄清楚它到底是什么。我只是在網上找不到一個直截了當的答案。
3 回答
紅顏莎娜
TA貢獻1842條經驗 獲得超13個贊
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 關注
- 665 瀏覽
添加回答
舉報
0/150
提交
取消
