c ++中的继承问题 [英] Inheritance problem in c++
本文介绍了c ++中的继承问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好
我面临继承问题。
i make
如果上课a {
受保护:
int i;
}
class b:public a {
预计:
int j;
}
main(){
a * obj = new a()
ai? //不显示
}
为什么不显示?
你可以解释一下吗?
Hello
I am facing a problem in inheritance.
i make
if make class a {
protected:
int i;
}
class b:public a{
projected:
int j;
}
main(){
a * obj=new a()
a.i ? // not display
}
why it is not display ?
can you please explain?
推荐答案
这个问题与继承无关;你永远不会在代码示例中使用继承:在main
函数中,类b
完全被忽略。
问题是受保护
。毕竟,阅读有关访问说明符的任何C ++手册。要从某些类外部访问某些内容,请将其设为public
;protected
仅允许访问派生类型。
-SA
The question has nothing to do with inheritance; you never use inheritance in your code sample: in themain
function, the classb
is totally ignored.
The problem isprotected
. After all, read any C++ manual about the access specifiers. To make something accessible from outside some class, make itpublic
;protected
allows access only to derived types.
—SA
在main()
中,ai
是不可见的。a
是可以访问的,因为它是在main()
中声明的变量,但是如果i
被声明为protected
或private
,你无法访问它。
protected
表示类中的类和所有派生类,a
在这种情况下,将获得对指定成员的访问权限。非派生类和全局函数将无法访问相关类的受保护成员。
因此,因为main
不是派生自a
的类,实际上是一个全局函数,你无法访问受保护的成员i
。
我希望这个答案不会太晚,我希望你做一些研究。这不是一个概念太难了。
Withinmain()
,a.i
is invisible.a
is accessible because it''s a variable declared withinmain()
, but ifi
is declared eitherprotected
orprivate
, you can''t access it.
protected
means that the class and all derived classes from the class,a
in this case, will gain access to the specified member. Non-deriving classes and global functions will not have access to protected members of the class in question.
So, becausemain
is not a class deriving froma
and is in fact a global function, you can not access the protected memberi
.
I hope this answer isn''t too late, and I hope you do some research. This isn''t too tough of a concept.
这篇关于c ++中的继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文