简体   繁体   English

另一个结构内部的结构的运算符重载给出错误

[英]Operator overloading of struct inside another struct gives error

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

The above code gives error: 上面的代码给出了错误:
'MyStruct::Node MyStruct::operator+(const MyStruct::Node&, const MyStruct::Node&)' must take either zero or one argument . 'MyStruct::Node MyStruct::operator+(const MyStruct::Node&, const MyStruct::Node&)' must take either zero or one argument

While the following codes compiles correctly - 虽然以下代码可以正确编译-

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

and

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

How can I overload operator of Node outside the Node structure but inside MyStruct ? 如何在Node结构之外但在MyStruct内部重载Node运算符?

How can I overload operator of Node outside the Node structure but inside MyStruct? 如何在Node结构外部但在MyStruct内部重载Node的运算符?

You can't do that. 你不能那样做。 Any overload operators defined outside Node and inside MyStruct is treated as an overload operator of MyStruct . 外面所定义的任何过载操作符Node和内部MyStruct被视为过载操作者MyStruct This is where a namespace is different from a struct . 这是namespacestruct不同的地方。

You can use: 您可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM