C++ inherited class has member of same name

2019-06-15 01:36发布

In C++ you can put a member in a base class and a member with the same name in the inherited class.

How can I access a specific one in the inherited class?

标签: c++ class base
7条回答
▲ chillily
2楼-- · 2019-06-15 02:00

Yes.

Qualify your call, f(), with a class name: SpecificClass::f().

查看更多
贪生不怕死
3楼-- · 2019-06-15 02:04

In that case you should fully qualify a member name.

class A
{
public:
  int x;
};


class B : public A
{
public:
  int x;
  B() 
  { 
    x = 0;
    A::x = 1;
  }
};
查看更多
Viruses.
4楼-- · 2019-06-15 02:06

If you specify the name you'll access the one in the inherited class automatically. If you mean how do you access the one in the base class, use Base::member

查看更多
Fickle 薄情
5楼-- · 2019-06-15 02:07

One approach (already mentioned in all other answers) is to use the qualified member name, like Base::member. It can be used in conjunction with explicit access through this pointer, if that's your style: this->Base::member.

Another approach is to perform access through this pointer explicitly converted to the base class type: ((Base *) this)->member.

Of course, the above references to this pointer are made under assumption that you are trying to access the member from within some non-static member function of the class. To access if from "outside", the same tricks can be applied to any other pointer (or reference): some_pointer->Base::member or ((Base *) some_pointer)->member.

For data members these two approaches are equivalent. For member functions they can lead to different results with virtual functions. For this reason, in general, the first approach should be preferred.

查看更多
Deceive 欺骗
6楼-- · 2019-06-15 02:13

By prefixing it with classname::.

查看更多
对你真心纯属浪费
7楼-- · 2019-06-15 02:17

To access the hidden member in the base class you have to prefix the member name with the base class name. See below:

class A
{
protected:
   int i;
};

class B : public A
{
public:
   void foo( void )
   {
      int a_i = A::i;
      int b_i = i;
      int b_i_as_well = B::i;
   }
private:
   int i;
};
查看更多
登录 后发表回答