C++:重叠基类方法
当继承两个基类时,如果两个基类都具有相同名称和签名的方法,会发生什么情况?
class Physics
{
public:
void Update() { std::cout << "Physics!" }
};
class Graphics
{
public:
void Update() { std::cout << "Graphics!" }
};
class Shape : Physics, Graphics
{
};
int main()
{
Shape shape;
shape.Update();
}
会发生什么?
When inheriting two base classes, what happens if both have a method with the same name and signature?
class Physics
{
public:
void Update() { std::cout << "Physics!" }
};
class Graphics
{
public:
void Update() { std::cout << "Graphics!" }
};
class Shape : Physics, Graphics
{
};
int main()
{
Shape shape;
shape.Update();
}
What will happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,首先,无论是否调用
Update
,您的代码都不会编译:Update
成员函数缺少返回类型Shape
私有地继承自 < code>Physics 和Graphics
,因此Update
无法从main
访问现在,话虽如此,当您尝试调用时会发生什么
Update
是一个歧义,会导致编译错误。可以使用以下方法消除这种歧义:Well, first of all your code does not compile regardless of the call to
Update
:Update
member functions lack returns typesShape
inherits privately fromPhysics
andGraphics
, soUpdate
is inaccessible frommain
Now, that being said, what happens when you attempt to call
Update
is an ambiguity which will lead to a compilation error. This ambiguity may be lifted using :在这里找到https://gist.github.com/752273
Found here https://gist.github.com/752273
在这种情况下,它应该调用Physics::Update,因为您在定义继承时首先指定了这一点。实际上,在这种情况下它不会工作,因为它对你不可见,因为你没有指定公共继承,但如果你这样做了,你应该默认获得Physics::Update。您要做的最好的事情是通过编写 Shape::Update 并根据需要调用Physics::Update 和/或 Graphics::Update 来解决任何歧义。
In this case, it should call Physics::Update because you specified that first when you defined the inheritance. Actually, in this case it won't work because it's not visible to you because you didn't specify public inheritance, but if you did, you should get Physics::Update by default. The best thing for you to do is to resolve the any ambiguity by writing Shape::Update and having that call Physics::Update and/or Graphics::Update as necessary.