简体   繁体   中英

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 .

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 ?

How can I overload operator of Node outside the Node structure but inside MyStruct?

You can't do that. Any overload operators defined outside Node and inside MyStruct is treated as an overload operator of MyStruct . This is where a namespace is different from a struct .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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