How to access parent class's data member from child class, when both parent and child have the same name for the dat member

前端 未结 3 2547
粉色の甜心
粉色の甜心 2021-02-20 18:17

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 = Paren         


        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-20 19:12

    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.

提交回复
热议问题