首页 > 解决方案 > 另一个结构内结构的运算符重载会产生错误

问题描述

struct MyStruct {
  struct Node {
    int a;
  };
  Node operator + (const Node &A, const Node &B) {
    Node ret;
    ret.a = A.a + B.a;
    return ret;
  };
};

上面的代码给出了错误:
‘MyStruct::Node MyStruct::operator+(const MyStruct::Node&, const MyStruct::Node&)’ must take either zero or one argument

虽然以下代码可以正确编译 -

struct Node {
  int a;
};
Node operator + (const Node &A, const Node &B) {
  Node ret;
  ret.a = A.a + B.a;
  return ret;
};

struct MyStruct {
  struct Node {
    int a;
    Node operator + (const Node &B) {
      a += B.a;
      return *this;
    };
  };
};

如何重载结构Node外部Node但内部的运算符MyStruct

标签: c++structcompiler-errorsoperator-overloading

解决方案


如何在 Node 结构之外但在 MyStruct 内重载 Node 运算符?

你不能那样做。任何在外部Node和内部定义MyStruct的重载运算符都被视为 的重载运算符MyStruct。这就是 anamespace与 a 不同的地方struct

您可以使用:

struct MyStruct {
  struct Node {
    int a;
  };
};

MyStruct::Node operator+(MyStruct::Node const& A, MyStruct::Node const& B) {
   MyStruct::Node ret;
   ret.a = A.a + B.a;
   return ret;
}

推荐阅读