2

I have the following code:

class example {
   int x;
   inline void operator=(int value) { x = value; }
};

int main() {
   example foo { 100 };
   int bar = foo;
}

The int bar = foo; obviously doesn't work, because I'm trying to assign a variable of type example to a variable of type int.

Is it possible to retrieve the x variable without using a getter function and without using operator.? If so, is it still possible to do purely by code inside the struct, and keeping the int bar = foo; as is?

enzeys
  • 108
  • 9

1 Answers1

3

Add a conversion function to allow implicit conversion

struct example {
   int x;
   inline void operator=(int value) { x = value; }

   operator int() const
   {
       return x;
   }
};

int main() {
   example foo { 100 };
   int bar = foo;
}
user4581301
  • 33,082
  • 7
  • 33
  • 54