c++ - 另一个结构内结构的运算符重载会产生错误
问题描述
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
?
解决方案
如何在 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;
}
推荐阅读
- typescript - 打字稿与数据库的连接
- android - PlusShare 类已弃用。有没有其他替代方法可以从 android 应用程序在 google Plus 上分享?
- python - Python:如何在两个列表中引用相同的索引值位置?
- c# - Task.Run 然后使用异步等待 ContinueWith 在主线程替代上调用?
- python - NameError:在 wsadmin cli 实用程序的 jython 中使用布尔值时为真
- javascript - 刷新没有布局的div
- python - 使用带有 git clean 过滤器的黑色
- node.js - Mongoose - 返回单个文档而不是使用 Aggregate 的文档数组
- javascript - Stop repeating div content in PHP AJAX MySQL
- python - FLASK:每次有新请求进来时,路由器外的代码都会被执行吗?