[英]How to access member with same name in the inheritance
I have a question about how to access the member with the same name with inheritance. 我有一个关于如何通过继承访问具有相同名称的成员的问题。 For example, 例如,
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?
}
di
in your example refers to the i
in the derived class. 您的示例中的di
指的是派生类中的i
。
You can refer to the base class i
by qualifying it with the base class name: 您可以通过使用基类名称限定它来引用基类i
:
d.Base::i
In general, it's a bad idea to have derived classes with members having the same name as members in base classes. 通常,派生类的成员名称与基类中的成员名称相同是一个不好的主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.