C ++虚拟关键字vs覆盖函数 [英] c++ virtual keyword vs overriding function

查看:95
本文介绍了C ++虚拟关键字vs覆盖函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习c ++,并且正在学习virtual关键字.我搜寻了互联网,以至于无济于事.我进入编辑器并进行了以下实验,期望它可以将基本消息打印两次(因为我的印象是需要使用virtual关键字来覆盖函数).但是,它打印出两个不同的消息.有人可以向我解释为什么如果我们可以简单地覆盖函数并仍然看似多态的行为,那么为什么需要virtual关键字呢?也许将来有人可以帮助我和其他人了解虚拟与覆盖. (我得到的输出是我是基础",后跟我是派生的").

I am learning c++ and am learning about the virtual keyword. I have scoured the internet trying to understand it to no avail. I went into my editor and did the following experiment, expecting it to print out the base message twice (because I was under the impression that the virtual keyword is needed to override functions). However, it printed out two different messages. Can someone explain to me why we need the virtual keyword if we can simply override functions and still seemingly get polymorphic behavior? Perhaps someone can help me and other people in the future understand virtual vs. overriding. (The output I am getting is "I am the base" followed by "I am the derived").

#include <iostream>

using namespace std;
class Base{
public:
    void printMe(){
        cout << "I am the base" << endl;
    }
};
class Derived: public Base{
public:
    void printMe(){
        cout << "I am the derived" << endl;
    }
};
int main() {
    Base a;
    Derived b;
    a.printMe();
    b.printMe();
    return 0;
}

推荐答案

请考虑以下示例.说明virtualoverride需求的重要行是c->printMe();.请注意,c的类型为Base*,但是由于多态性,它可以正确地从派生类中调用重写的方法.

Consider the following example. The important line to illustrate the need for virtual and override is c->printMe();. Note that the type of c is Base*, however due to polymorphism it is correctly able to call the overridden method from the derived class.

#include <iostream>

class Base{
public:
    virtual void printMe(){
        std::cout << "I am the base" << std::endl;
    }
};

class Derived: public Base{
public:
    void printMe() override {
        std::cout << "I am the derived" << std::endl;
    }
};

int main() {
    Base a;
    Derived b;
    a.printMe();
    b.printMe();
    Base* c = &b;
    c->printMe();
    return 0;
}

输出为

I am the base
I am the derived
I am the derived

这篇关于C ++虚拟关键字vs覆盖函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆