在类中为结构体重载operator=运算符

3
我们有以下内容: (伪代码)
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;
}

然而,它无法编译。我们得到了一个类似于“missing ; before &”的错误。
“MyStruct must be a class or namespace if followed by ::”。 这里有什么概念我不理解吗?

1
你的operator=函数为什么有两个返回类型? - goji
1
你缺少资格证明。类外没有 MyStruct - chris
1
由于MyStruct位于MyClass内部,所以没有MyStruct::operator=。请使用MyClass::MyStruct::operator=。另外,不要忘记在MyStruct中声明operator= - syam
2个回答

3
你需要将 MyStructoperator= 移动到结构声明体中:
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;
}

抱歉,但我必须评论我实际看到的内容。 ;) - syam
为什么我们在这里使用 inline?它是必需的吗? - MrDuk
1
如果它在头文件中,那么就是的。否则你会得到多个定义错误。请参阅http://en.wikipedia.org/wiki/One_Definition_Rule - goji

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

MyStruct的正文中直接为运算符定义。另外请注意,我添加了惯用的return *this,让赋值操作返回对此对象的引用。 编辑:针对问题的编辑做出回应。 你也可以在正文中声明运算符,然后在别处定义它。在这种情况下,语法是:
MyClass::MyStruct& MyClass::MyStruct::operator=(const MyOtherStruct& rhs) {
   // assignment logic goes here
   return *this;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接