C++ Inheritance of functions with same name

前端 未结 1 1894
旧巷少年郎
旧巷少年郎 2021-01-23 06:48

I have the following class declarations:

class human
{
    public:
    void msg(){cout<<\"I am human\\n\";}
};
class John:public human 
{
    public:
    v         


        
相关标签:
1条回答
  • 2021-01-23 07:08

    "But doesnt John inherit msg() from human?"

    Yes it does, but hides it with its own implementation.

    "Also is there a way to access msg() of human?"

    Yes, you need to explicitly state the class scope (as long human::msg() is in public scope as it was originally asked):

      John a;
      a.human::msg();
     // ^^^^^^^
    

    The same syntax needs to be applied if you want to access human::msg() from within class John:

    class John : public human {
        public:
        void msg() {cout<<"I am a John\n";}
        void org_msg() { human::msg(); }
    };
    
    John a;
    a.org_msg();
    

    or another alternative

    John john;
    human* h = &john;
    h->msg();
    
    0 讨论(0)
提交回复
热议问题