简体   繁体   中英

Call parent's public member function outside of class

So here is an example what I would like to do in function main . Example, watch my comment between the lines:

#include <stdio.h>

class A {
public:
    void msg()
    {
        puts("from A");
    }
};

class B : public A {
public:
    void msg()
    {
        puts("from B");
    }
};

int main()
{
    A a;
    B b;

    a.msg();
    b.msg(); // This must print out B
    b.msg(); // And I want this to print A. What is the syntax for that?
}

I do not want add extra code to this, just may be some synthatic sugar. Something like A::b.msg , but it did not work

You can use the following:

b.A::msg(); //will call msg from the class A

But maybe you should be looking at a different pattern?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM