为了账号安全,请及时绑定邮箱和手机立即绑定

如果我要重写基类的虚函数,可以调用它吗?

如果我要重写基类的虚函数,可以调用它吗?

C++
牧羊人nacy 2019-11-22 15:37:20
假设我有课程,Foo并且Bar设置如下:class Foo{public:    int x;    virtual void printStuff()    {        std::cout << x << std::endl;    }};class Bar : public Foo{public:    int y;    void printStuff()    {        // I would like to call Foo.printStuff() here...        std::cout << y << std::endl;    }};如代码中所注释的那样,我希望能够调用我要重写的基类的函数。在Java中有super.funcname()语法。这在C ++中可能吗?
查看完整描述

3 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

C ++语法如下:


class Bar : public Foo {

  // ...


  void printStuff() {

    Foo::printStuff(); // calls base class' function

  }

};


查看完整回答
反对 回复 2019-11-22
?
MYYA

TA贡献1868条经验 获得超4个赞

是,


class Bar : public Foo

{

    ...


    void printStuff()

    {

        Foo::printStuff();

    }

};

它与superJava中的相同,不同之处在于它允许您在具有多个继承时从不同的基础调用实现。


class Foo {

public:

    virtual void foo() {

        ...

    }

};


class Baz {

public:

    virtual void foo() {

        ...

    }

};


class Bar : public Foo, public Baz {

public:

    virtual void foo() {

        // Choose one, or even call both if you need to.

        Foo::foo();

        Baz::foo();

    }

};


查看完整回答
反对 回复 2019-11-22
?
哔哔one

TA贡献1854条经验 获得超8个赞

有时,当您不在派生函数中时,您需要调用基类的实现...它仍然有效:


struct Base

{

    virtual int Foo()

    {

        return -1;

    }

};


struct Derived : public Base

{

    virtual int Foo()

    {

        return -2;

    }

};


int main(int argc, char* argv[])

{

    Base *x = new Derived;


    ASSERT(-2 == x->Foo());


    //syntax is trippy but it works

    ASSERT(-1 == x->Base::Foo());


    return 0;

}


查看完整回答
反对 回复 2019-11-22
  • 3 回答
  • 0 关注
  • 455 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信