Equals operator

I have a class. The class contains only one type, an integer.

It is possible to set the integer by overloading the equals operator.

Therefore, allowing me to write...

 
myClass = 123;


instead of...

 
myClass.theint = 123;



Is it, however, possible to overload an operator that would allow me to write...

 
int i = myClass;


instead of...

 
int i = myClass.theint;


?

Thanks
= is the assignment operator. The equals operator is ==.

myClass = 123; will work fine if you have a (non-explicit) constructor that takes an int.
1
2
3
4
5
6
7
8
9
10
11
12
struct MyClass
{
	int theint;
	MyClass() : theint(0) {}
	MyClass(int i) : theint(i) {}
};

int main()
{
	MyClass myClass;
	myClass = 123;
}

But you can also overload the assignment operator.
1
2
3
4
5
6
7
8
9
10
11
12
struct MyClass
{
	int theint;
	MyClass() : theint(0) {}
	MyClass& operator=(int i) {theint = i; return *this;}
};

int main()
{
	MyClass myClass;
	myClass = 123;
}



You can allow the class instance to be implicitly converted to an int by overloading operator int.
1
2
3
4
5
6
7
8
9
10
11
12
struct MyClass
{
	int theint;
	MyClass() : theint(0) {}
	operator int() {return theint;}
};

int main()
{
	MyClass myClass;
	int i = myClass;
}


Last edited on
All what you need is to define a conversion constructor and a conversion function.

For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

class MyClass
{
public:
   MyClass( int i = 0 ) : theint( i ) {}
   operator int() const { return ( theint ); }
private:
   int theint;
};

int main()
{
   MyClass obj;

   obj = 10;

   std::cout << "obj = " << obj << std::endl;

   int i = obj;

   std::cout << "i = " << i << std::endl;

   return ( 0 );
};
Last edited on
Nice one :)
Topic archived. No new replies allowed.