How to access parent class's data member from

2019-04-05 17:30发布

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.

3条回答
家丑人穷心不美
2楼-- · 2019-04-05 17:55

Almost got it:

this->x = Parent::x;

this is a pointer.

查看更多
3楼-- · 2019-04-05 18:02

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.

C++ provides a so-called, "scope operator" (::), which is perfectly suited to your task.

More details are provided at this page. You can combine this operator with class name (Parent) to access parent's x variable.

查看更多
疯言疯语
4楼-- · 2019-04-05 18:16

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.

查看更多
登录 后发表回答