C ++继承类具有同名成员

问题描述 投票:13回答:7

在C ++中,您可以将成员放在基类中,并在继承的类中使用相同名称的成员。

如何访问继承类中的特定类?

c++ class base
7个回答
28
投票

在这种情况下,您应该完全限定成员名称。

class A
{
public:
  int x;
};


class B : public A
{
public:
  int x;
  B() 
  { 
    x = 0;
    A::x = 1;
  }
};

7
投票

如果指定名称,则将自动访问继承类中的名称。如果您的意思是如何访问基类中的那个,请使用Base :: member


6
投票

要访问基类中的隐藏成员,必须在成员名称前加上基类名称。见下文:

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
投票

是。

使用类名:f()验证您的电话SpecificClass::f()


3
投票

classname::作为前缀。


3
投票

一种方法(在所有其他答案中已经提到)是使用合格的成员名称,如Base::member。它可以与this指针的显式访问结合使用,如果这是你的风格:this->Base::member

另一种方法是通过this指针执行访问,显式转换为基类类型:((Base *) this)->member

当然,上面对this指针的引用是在假设您尝试从类的某些非静态成员函数中访问该成员的情况下进行的。要从“外部”访问,相同的技巧可以应用于任何其他指针(或引用):some_pointer->Base::member((Base *) some_pointer)->member

对于数据成员,这两种方法是等效的。对于成员函数,它们可以通过虚函数导致不同的结果。因此,一般来说,第一种方法应该是首选。


1
投票
#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.
}
© www.soinside.com 2019 - 2024. All rights reserved.