C++ 如何从子类访问父类的数据成员,当父类和子类的 dat 成员具有相同的名称时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11525418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access parent class's data member from child class, when both parent and child have the same name for the dat member
提问by codeLover
my scenario is as follows::
我的情况如下:
class Parent
{
public:
int x;
}
class Child:public Parent
{
int x; // Same name as Parent's "x".
void Func()
{
this.x = Parent::x; // HOW should I access Parents "x".
}
}
Here how to access Parent's "X" from a member function of Child.
这里如何从 Child 的成员函数访问 Parent 的“X”。
回答by Luchian Grigore
Almost got it:
差点就明白了:
this->x = Parent::x;
this
is a pointer.
this
是一个指针。
回答by Chad
Accessing it via the scope resolution operator will work:
通过范围解析运算符访问它会起作用:
x = Parent::x;
However, I would question in what circumstances you want to do this. Your example uses public inheritance which models an "is-a" relationship. So, if you have objects that meet this criteria, but have the same members with different values and/or different meanings then this "is-a" relationship is misleading. There may be some fringe circumstances where this is appropriate, but I would state that they are definitely the exceptions to the rule. Whenever you find yourself doing this, think long and hard about why.
但是,我会质疑您要在什么情况下执行此操作。您的示例使用公共继承来建模“is-a”关系。因此,如果您有满足此条件的对象,但具有具有不同值和/或不同含义的相同成员,那么这种“is-a”关系具有误导性。可能有一些边缘情况是合适的,但我要声明它们绝对是规则的例外。每当您发现自己这样做时,请仔细思考原因。
回答by M. Grzywaczewski
It's only a brief explaination of solutions provided by Luchian Grigore and Mr. Anubis, so if you are curious 'how this works', you should read it further.
这只是 Luchian Grigore 和 Anubis 先生提供的解决方案的简要说明,因此如果您对“这是如何工作的”感到好奇,您应该进一步阅读。
C++ provides a so-called, "scope operator" (::
), which is perfectly suited to your task.
C++ 提供了一个所谓的“作用域运算符”( ::
),它非常适合您的任务。
More details are provided at this page. You can combine this operator with class name (Parent
) to access parent's x
variable.
此页面提供了更多详细信息。您可以将此运算符与类名 ( Parent
)结合使用以访问父级x
变量。