YaoRaoLov 2008-12-10 19:35 采纳率: 50%
浏览 192
已采纳

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

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 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)