0
votes

I want to overload the operator = and I have the following operator-function

int IntegerClass::operator=(IntegerClass integer) {
  return  integer.number;
}

This should be correct?

In another class I want to assign the objects private member (int) to another int i.e.

int x = integerClass; 

but when I compile I get the following error

error: cannot convert 'std::IntegerClass' to 'int' in initialization

What is wrong with my implementation of operator-overloading and how should the function look like?

1
int x = integerClass doesn't invoke any operators (it is initialization and not assignment), and especially not IntegerClass::operator=. If any, you could try implementing IntegerClass::operator int() instead to support implicit conversion to int. - user529758
What is this std::IntegerClass? The standard library doesn't have such a class AFAIK. You added your class to std? That's bad. - leemes
@leemes .. It may be due to that Eclipse autogenerates a namespace that embraces the whole class .i.e namespace std { class IntegerClass {} } ? - user2991252
Eclipse is your IDE; if that was true you'd see the code. - leemes

1 Answers

4
votes

Your operator overloads assignment of one IntegerClass to another, but you're trying to assign (actually it's initialization) to a built in int. You need to define an implicit conversion operator.

The code should be something like this (sorry I don't remember the exact syntax)

IntegerClass::operator int() {
  return number;
}