【问题标题】:C++: Overlapping base class methodsC++:重叠基类方法
【发布时间】:2023-03-03 10:10:01
【问题描述】:

当继承两个基类时,如果两个基类的方法名称和签名相同会怎样?

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();
}

会发生什么?

【问题讨论】:

  • 您试图在形状类中调用未定义的函数“更新”,这在 main 中是无法访问的。

标签: c++ class inheritance multiple-inheritance overloading


【解决方案1】:

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

  • Update 成员函数缺少返回类型
  • Shape 私下继承自 PhysicsGraphics,所以 Update 无法从 main 访问

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

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

【讨论】:

  • 我同意 Shape 从 Graphics and Physics 私下继承。为什么 g++ 没有抱怨那部分?
  • @EnabrenTane 我从未编译过它。这都是理论上的。
  • @Jay 我确实编译了一个更正的示例并在下面发布了生成的错误。
  • @user542687 不,这不是理论,而是问题的正确答案。
【解决方案2】:

在这里找到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()

【讨论】:

    【解决方案3】:

    在这种情况下,它应该调用 Physics::Update,因为您在定义继承时首先指定了它。实际上,在这种情况下它不起作用,因为它对您不可见,因为您没有指定公共继承,但如果您这样做了,您应该默认获得 Physics::Update。最好的办法是通过编写 Shape::Update 并根据需要调用 Physics::Update 和/或 Graphics::Update 来解决任何歧义。

    【讨论】:

      猜你喜欢
      • 2017-04-03
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多