[英]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
. 这是
namespace
与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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.