-1

For some reason my overloaded operators work fine when I compile on visual studio but when I compile on g++ in linux I get the following errors:

main.cpp:66:4: error: no match for ‘operator=’ (operand types are ‘UVLI’ and ‘UVLI’) f = a + b;

For some reason it appears to be looking for an overloaded operator= which takes UVLI, UVLI and I don't know why.

Here are my operators:

UVLI UVLI::operator+(unsigned long number) const
{
     UVLI result, right;        
     UVLI left((*this));

    right.long2UVLI(number);
    result.add(left, right);
    return result;
}

UVLI UVLI::operator+(UVLI &right) const
{
    UVLI result;
    UVLI left((*this));

    result.add(left, right);
    return result;
}

void UVLI::operator=(unsigned long number)
{

    this->long2UVLI(number);
    return;
}

 void UVLI::operator= (UVLI &right)
{
    this->copy(right);
    return;
}

All I am doing in my main function is:

UVLI f;
f = a + b;

Does anyone know why g++ is not using my + operator, and instead trying to find =(UVLI, UVLI)?

I'm not to worried of the contents inside of the operator is wrong, I just want it to call correctly.

Thanks.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • And what's the actual declaration of `UVLI` please? – πάντα ῥεῖ Oct 05 '14 at 00:33
  • 4
    Non-const lvalue references cannot be bound to a temporary. MSVC has a terrible language extension that allows that. I strongly suggest you look at how to overload operators [properly](http://stackoverflow.com/questions/4421706/operator-overloading). – chris Oct 05 '14 at 00:33
  • Thanks @chris ! Back to the drawing board for me. – copy_god Oct 05 '14 at 00:38
  • You just need to change `UVLI &right` to `UVLI const &right` to fix this. – M.M Oct 05 '14 at 01:02
  • What is the data in UVLI? It may be the case the default assignment operator is fine. If you have an implicit constructor that takes `unsigned long`, then you don't need the assignment operator for it as well, except as a micro-optimization. – Neil Kirk Oct 05 '14 at 02:10
  • @chris It is one of my favorite language extensions – Neil Kirk Oct 05 '14 at 02:11

1 Answers1

-1

Your assignment operators need to take const references, and their return type should be UVLI&. Assignment operators must follow this strict form:

UVLI& operator = (const UVLI& that) {
    this->copy(that);
    return *this;
}

The main reason for this is to allow operator chaining:

UVLI a;
UVLI b;
UVLI c;
UVLI d = c = a + b;
d3coy
  • 395
  • 1
  • 4
  • 1
    "Assignment operators must follow this strict form" no they don't. – T.C. Oct 05 '14 at 02:03
  • That is the recommended function signature for common usage, but they don't have to. The error isn't simply because the operator didn't follow that signature, but another reason. – Neil Kirk Oct 05 '14 at 02:11
  • Yuck, I thought that was a language requirement. Maybe I'm thinking of copy assignment operators. Too much of this language is held together by convention. – d3coy Oct 05 '14 at 02:19