猿问

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

假设我有课程,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 ++中可能吗?


牧羊人nacy
浏览 493回答 3
3回答

呼唤远方

C ++语法如下:class Bar : public Foo {&nbsp; // ...&nbsp; void printStuff() {&nbsp; &nbsp; Foo::printStuff(); // calls base class' function&nbsp; }};

MYYA

是,class Bar : public Foo{&nbsp; &nbsp; ...&nbsp; &nbsp; void printStuff()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Foo::printStuff();&nbsp; &nbsp; }};它与superJava中的相同,不同之处在于它允许您在具有多个继承时从不同的基础调用实现。class Foo {public:&nbsp; &nbsp; virtual void foo() {&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }};class Baz {public:&nbsp; &nbsp; virtual void foo() {&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }};class Bar : public Foo, public Baz {public:&nbsp; &nbsp; virtual void foo() {&nbsp; &nbsp; &nbsp; &nbsp; // Choose one, or even call both if you need to.&nbsp; &nbsp; &nbsp; &nbsp; Foo::foo();&nbsp; &nbsp; &nbsp; &nbsp; Baz::foo();&nbsp; &nbsp; }};

哔哔one

有时,当您不在派生函数中时,您需要调用基类的实现...它仍然有效:struct Base{&nbsp; &nbsp; virtual int Foo()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; }};struct Derived : public Base{&nbsp; &nbsp; virtual int Foo()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return -2;&nbsp; &nbsp; }};int main(int argc, char* argv[]){&nbsp; &nbsp; Base *x = new Derived;&nbsp; &nbsp; ASSERT(-2 == x->Foo());&nbsp; &nbsp; //syntax is trippy but it works&nbsp; &nbsp; ASSERT(-1 == x->Base::Foo());&nbsp; &nbsp; return 0;}
随时随地看视频慕课网APP
我要回答