c++ - 在另一个结构中重载结构的运算符会出错

标签 c++ struct compiler-errors operator-overloading

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&)”必须采用零个或一个参数

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

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 结构之外但在 MyStruct 内部重载 Node 的运算符?

最佳答案

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

你不能那样做。在 Node 外部和 MyStruct 内部定义的任何重载运算符都被视为 MyStruct 的重载运算符。这就是 namespacestruct 的不同之处。

您可以使用:

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

关于c++ - 在另一个结构中重载结构的运算符会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54914647/

相关文章:

c# - 遍历从 C# 传递的未知 C 结构

iphone - __unsafe_unretained NSString 结构变量

c++ - 错误: variable or field 'functionName' declared void

C++消息传递疑惑

c++ - 将 WAV 文件音频输入转换为纯 ASCII 字符

c++ - 为遗传算法分配和检索按位存储值

Thrift 生成结构的 C++ 大括号初始化

c++ - 当我在结构中包含多个数组时,我的程序跳过了一堆代码

javascript - Parcel 错误 - 找不到模块 @parcel\fs-search\fs-search.win32-x64-msvc.node

android - 在 active-android 中发现意外的元数据类型