Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator= for structs, within classes

We have the following: (pseudoish)

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

We'd like to overload the = operator in the MyClass.cpp to do something like:

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

However, it doesn't want to compile. We're getting an error similar to

"missing ; before &"

and

"MyStruct must be a class or namespace if followed by ::"

Is there some concept here I'm missing?

like image 559
MrDuk Avatar asked Feb 01 '26 21:02

MrDuk


1 Answers

You need to move your operator= for MyStruct into the struct declaration body:

class MyClass
{
    private:
       struct MyStruct{
          int am1;
          int am2;

          MyStruct& operator=(const MyOtherStruct& rhs)
          {
             am1 = rhs.am1;
             am2 = rhs.am2;
             return *this;
          }
       };
};

Or if that's not possible because MyOtherStruct is incomplete or don't want to clutter the class declaration:

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;
}
like image 53
goji Avatar answered Feb 04 '26 11:02

goji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!