C ++同名的函数的继承 [英] C++ Inheritance of functions with same name
问题描述
我有以下类声明:
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
但不会 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 >
解决方案
em>但是约翰不从人类继承msg()
自己的实现。
还有一种方法来访问人类的msg >
是的,需要显式声明类范围(长
human :: msg()
在公共范围内,因为它最初被问到):John a;
a.human :: msg();
// ^^^^^^^
需要应用相同的语法if您希望从
类中访问
:human :: msg()
:Johnclass 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
andhuman
both have a functionmsg()
. Clearly , the classJohn
is inheriting resources fromhuman
. Now when I create an object of the derived class and callmsg()
:John a; a.msg();
The output is :
I am John
But doesnt
John
inheritmsg()
fromhuman
?Also is there a way to access
msg()
ofhuman
by using an object of the derived class?EDIT:
Yup calling the function like so will help me
a.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()
ofhuman
.解决方案"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 classJohn
: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();
这篇关于C ++同名的函数的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!