如何在继承中访问具有相同名称的成员

sky*_*oor 1 c++

我有一个关于如何使用继承访问具有相同名称的成员的问题.例如,

class Base { 

public:
int i;  

};
class Derived1 : public Base {

    public:
    int i;

    // how to access the i in the base class here?
};

int main() {

  Derived1 d;
  cout<<d.i;                          //which is it is?

  //how to access the different i here? 

}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 10

d.i在您的示例中引用i派生类中的.

您可以i通过使用基类名称对其进行限定来引用基类:

d.Base::i
Run Code Online (Sandbox Code Playgroud)

通常,使用与基类中的成员具有相同名称的成员的派生类是个坏主意.