亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果我要重寫基類的虛函數,可以調用它嗎?

如果我要重寫基類的虛函數,可以調用它嗎?

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 關注
  • 545 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號