喵-见缝插针 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条)

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝