喵-见缝插针 2008-12-10 19:35 采纳率: 0%
浏览 257
已采纳

如何从派生类函数调用父类函数?

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?

转载于:https://stackoverflow.com/questions/357307/how-to-call-a-parent-class-function-from-derived-class-function

  • 写回答

6条回答 默认 最新

  • 衫裤跑路 2008-12-10 19:57
    关注

    I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

    If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.

    class left {
    public:
        void foo();
    };
    
    class right {
    public:
        void foo();
    };
    
    class bottom : public left, public right {
    public:
        void foo()
        {
            //base::foo();// ambiguous
            left::foo();
            right::foo();
    
            // and when foo() is not called for 'this':
            bottom b;
            b.left::foo();  // calls b.foo() from 'left'
            b.right::foo();  // call b.foo() from 'right'
        }
    };
    

    Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

    class bottom : public left, public left { // Illegal
    };
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码