本文介绍了C ++同名的函数的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有以下类声明: class human { public: void msg(){cout<<I am human\\\;} }; class John:public human { public: void msg(){cout<<我是John \\\;} }; 显然, John human 都有一个函数 msg()。显然, John 类继承了来自 human 的资源。现在,当我创建一个派生类的对象并调用 msg(): John a; a.msg(); 输出为:但不会 John 继承 msg()从人? 也有一种方法来访问人 msg() $ c>通过使用派生类的对象? 编辑: 这样会帮助我 a.human :: msg() 另一个问题: 另外一个问题:如果我修改类,像这样:pre class human { protected: void msg(){cout< I am human\\\;} }; class John:public human { public: void msg(){cout<<我是John \\\;} }; 现在我如何访问 msg > 解决方案 自己的实现。是的,需要显式声明类范围(长 human :: msg()在公共范围内,因为它最初被问到): John a; a.human :: msg(); // ^^^^^^^ 需要应用相同的语法if您希望从类中访问 human :: msg():John : class John:public human { public: void msg(){cout< } void org_msg(){human :: msg(); } }; John a; a.org_msg(); 或另一个替代 John john; human * h =& john; h-> msg(); I have the following class declarations:class human{ public: void msg(){cout<<"I am human\n";}};class John:public human { public: void msg(){cout<<"I am a John\n";}};As it is clear the class John and human both have a function msg(). Clearly , the class John is inheriting resources from human. Now when I create an object of the derived class and call msg():John a;a.msg();The output is :But doesnt John inherit msg() from human? Also is there a way to access msg() of human by using an object of the derived class? EDIT:Yup calling the function like so will help mea.human::msg()Another question :Also if I modify the class like so:class human{ protected: void msg(){cout<<"I am human\n";}};class John:public human { public: void msg(){cout<<"I am a John\n";}};Now how can I access the msg() of human. 解决方案 Yes it does, but hides it with its own implementation.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 alternativeJohn john;human* h = &john;h->msg(); 这篇关于C ++同名的函数的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-27 17:21