c++ Multiple parents with same variable name

夙愿已清 提交于 2019-12-05 19:20:10

问题


class A{
    protected:
    int var;
};

class B{
    protected:
    int var;
};

class C : public A, public B {};

What happens here? Do the variable merges? Can I call one in specific like, B::var = 2, etc.


回答1:


You class C will have two variables, B::var and A::var. Outside of C you can access them like this (if you change to public:),

C c;
c.A::var = 2;

Attempting to access c.var will lead to an error, since there is no field with the name var, only A::var and B::var.

Inside C they behave like regular fields, again, with the names A::var and B::var.




回答2:


You can access them in class C by A::var and B::var respectively.

Here is a link that covers the same problem.




回答3:


If you only refer to var inside of C, the compiler does not know whether you mean A::var or B::var and the compiler will tell you that var is ambiguous. Therefore, you have to fully qualify the name when using var.

No merging happens, any instance of C will contain both variables.



来源:https://stackoverflow.com/questions/12255087/c-multiple-parents-with-same-variable-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!