Assignment operator overloading

I have a class called Device with private field ID,Type and Number. I have a bigger project but i will present only a little part here. Let's say i create an object of this class in the main and then i want to overload the > operator in order to check if the ID field of the object is bigger than a variable defined in the main called max.
i then want..

1
2
3
4
5
6
Device obj;
int max;
if (obj>max)
   {
    .....
    }


for this overloading i used the following code

1
2
3
4
5
6
7
bool device::operator>(const int& code)
{
	if (ID > code)
		return true;
	else return false;

}


and it is working fine...
now i want to set..
 
max=obj;


where i mean the field ID of obj is equal to max..
can you help me?
i think is difficult because usually the object is the left-part of the = but now is the right part, so i guess there is some specific code.
Did you mean max == obj; instead of max=obj;?

As for the first your operator it can be written simpler

1
2
3
4
bool device::operator>( int code ) const
{
	return ( ID > code );
}


As for the second operator then your class has to have some conversion function or you need to write two overload operators.
Last edited on
well no..i meant max=obj..
i need to write this..

1
2
3
4
5
if (obj > max)
 {  

 max=obj; 
 }


that's why i need to overload the assignment operator
You may not overload the assignment operator for fundamental types. In this case you are speaking about you have to have a conversion function. For example

1
2
3
4
device::operator int() const
{
	return ID;
}
Last edited on
Oh that worked!! thank you very much!!!
Or you can define it inside the class definition even the following way that maybe will be better

1
2
3
4
explicit operator int() const
{
	return ID;
}



max = static_cast<int>( obj );
Last edited on
Topic archived. No new replies allowed.