重载运算符=,用于类中的结构

Overloading operator= for structs, within classes

本文关键字:结构 用于 运算符 重载      更新时间:2023-10-16

我们有以下内容:(伪)

class MyClass
{
    private:
       struct MyStruct{
          MyStruct operator=(const MyOtherStruct& rhs);
          int am1;
          int am2;
       };
};

我们想重载 MyClass 中的 = 运算符.cpp执行以下操作:

MyStruct&
MyStruct::operator=(const MyOtherStruct& rhs)
{
   am1 = rhs.am1;
   am2 = rhs.am2;
}

但是,它不想编译。我们收到类似于

"失踪 ;之前 &"

"MyStruct 必须是类或命名空间,如果后跟 ::"

这里有我缺少一些概念吗?

您需要将

MyStruct operator=移动到结构声明正文中:

class MyClass
{
    private:
       struct MyStruct{
          int am1;
          int am2;
          MyStruct& operator=(const MyOtherStruct& rhs)
          {
             am1 = rhs.am1;
             am2 = rhs.am2;
             return *this;
          }
       };
};

或者,如果由于MyOtherStruct不完整或不想弄乱类声明而无法做到这一点:

class MyClass
{
    private:
       struct MyStruct{
          int am1;
          int am2;
          MyStruct& operator=(const MyOtherStruct& rhs);
       };
};
inline MyClass::MyStruct& MyClass::MyStruct::operator=(const MyOtherStruct& rhs)
{
    am1 = rhs.am1;
    am2 = rhs.am2;
    return *this;
}

语法是

MyStruct& operator=(const MyOtherStruct& rhs) {
   // assignment logic goes here
   return *this;
}

对于直接在MyStruct体内的操作员.另请注意,我添加了惯用return *this,让赋值返回对此对象的引用。

编辑

以响应OP编辑问题。您还可以在正文中声明运算符,并在其他地方定义它。在本例中,语法为:

MyClass::MyStruct& MyClass::MyStruct::operator=(const MyOtherStruct& rhs) {
   // assignment logic goes here
   return *this;
}