C++覆盖子类中的函数成员

标签 c++ g++ overriding

class Foo
{
    public:
        void    action();
};

class Bar : public Foo
{
    public:
        void    action();
};

void Foo::action ()
{
    cout << "parent\n";
};

void Bar::action ()
{
    cout << "child\n";
};



int main()
{
    Foo* foo = new Bar ();
    foo->action();          // returns "parent" - "child" expected

    return 1;
 }

对于一个可能微不足道的问题,我很抱歉,但我是 C++ 的新手... 'foo' 指针必须指向 Foo 类的一个实例,因为它可以是 Foo 的任何子类,例如Bar、Bar1、Bar2、Bar3 等

同时“foo->action()”应该运行一个被覆盖的子函数。 请告诉我,我该如何更正代码以达到我的目标...... 谢谢!

最佳答案

与 Java 等其他语言不同,C++ 中的基类必须使用关键字 virtual 专门标记它允许覆盖的方法

关于C++覆盖子类中的函数成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11826198/

相关文章:

PHP 5.4 : why can classes override trait methods with a different signature?

javascript - 如何在 JS (Javascript) 中重载对象的构造函数?

C++ Windows 线程和互斥问题

C++:链接库消失并在执行期间出现段错误

c++ - && 在此代码中的优势是什么?

c++ - 使用 g++ 编译主模块的奇怪错误

c++ - Nana 用 C++ 制作 GUI

android - 在自定义 View 中覆盖空方法并在 MainActivity 中处理它

c++ - 解析编译错误 : no matching function for call to 'std::pair<,>::pair()'

c++ - 在 C++ 中将队列实例化为类成员