C++ inherited class has member of same name

2019-06-15 01:55发布

问题:

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?

回答1:

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;
  }
};


回答2:

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



回答3:

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;
};


回答4:

Yes.

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



回答5:

By prefixing it with classname::.



回答6:

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.



回答7:

#include <iostream>
using namespace std;

struct Base {
    int memfcn();
};

struct Derived : Base {
    int memfcn(int);
};

int main() {
    Derived d;
    Base b;
    d.Base::memfcn();  //you can even use :: in conjunction with dot(.). This is new to me.
}


标签: c++ class base