C++:重叠基类方法

发布于 2024-10-09 00:47:25 字数 337 浏览 0 评论 0原文

当继承两个基类时,如果两个基类都具有相同名称和签名的方法,会发生什么情况?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

寄居人 2024-10-16 00:47:25

好吧,首先,无论是否调用 Update ,您的代码都不会编译:

  • Update 成员函数缺少返回类型
  • Shape 私有地继承自 < code>Physics 和 Graphics,因此 Update 无法从 main 访问

现在,话虽如此,当您尝试调用时会发生什么Update 是一个歧义,会导致编译错误。可以使用以下方法消除这种歧义:

shape.Physics::Update();
shape.Graphics::Update();

Well, first of all your code does not compile regardless of the call to Update :

  • The Update member functions lack returns types
  • Shape inherits privately from Physics and Graphics, so Update is inaccessible from main

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 :

shape.Physics::Update();
shape.Graphics::Update();
何以笙箫默 2024-10-16 00:47:25

在这里找到https://gist.github.com/752273

$ g++ test.cpp 
    test.cpp: In function ‘int main()’:
    test.cpp:22: error: request for member ‘Update’ is ambiguous
    test.cpp:12: error: candidates are: void Graphics::Update()
    test.cpp:6: error:                 void Physics::Update()

Found here https://gist.github.com/752273

$ g++ test.cpp 
    test.cpp: In function ‘int main()’:
    test.cpp:22: error: request for member ‘Update’ is ambiguous
    test.cpp:12: error: candidates are: void Graphics::Update()
    test.cpp:6: error:                 void Physics::Update()
红颜悴 2024-10-16 00:47:25

在这种情况下,它应该调用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文