• Advertisement
Sign in to follow this  

operator overloading

This topic is 3701 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I can't get this to work at all but I can't see anything wrong with it :(
#include <iostream>

class number
{
	int value;
	public:
	number(){value = 0;}
	~number(){}

	int operator = (const number &obj)
	{
		return obj.value;
	}
	number & operator = (const int &integer)
	{
		value = integer;
		return *this;
	}
};

int main()
{
	number num = 50;  //cannot convert from 'int' to 'number'
	int integer = num;//cannot convert from 'number' to 'int'
	std::cout << integer << "\n";

	system("pause");
	return 0;
}

Share this post


Link to post
Share on other sites
Advertisement
Your assignments are actually assignments, they're initializations. In the first one you need a constructor argument that accepts an integer. ex:

number(int i) : value(i) {}

For the second one, you need a conversion from number to int. Ex:

operator int() { return value; }

Share this post


Link to post
Share on other sites

number num = 50; //cannot convert from 'int' to 'number'


This does not mean "make a number called 'num', and then assign 50 to it with the assignment operator". It means "make a number called 'num', passing 50 to a constructor which accepts one argument". It is exactly equivalent to "number num(50);". This is a special case: writing the '=' on the same line that you declare the variable asks for an initialization, not an assignment. These are different things.

Meanwhile, you cannot define the operation "assign an int from a user-defined class". That operator would have to belong to the int class, but int isn't a class, and even if it were, you wouldn't be able to modify it. Instead, you define the operation "interpret myself as an int". This is done like - well, like SiCrane said.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement