1

I'm trying to implement the following operator:

void operator=(const mpz_t &a, const myDatatype &b);

I need this operator to convert a variable from myDatatype to mpz_t from GMP (mpz_t x = y, where y has the datatype myDatatype). In the header file, I declare this function outside of the class. However, I have some other '=' operator declarations inside, since I want to convert variables of other datatypes to myDatatype.

class myDatatype {

public:
    //variable, constructors and destructor declaration
    ...



    void operator=(const mpz_t &a);
    void operator=(const myDatatype &a);

    //some methods

};

void operator=(const mpz_t &a, const myDatatype &b);

The error I get is:

error: ‘void operator=(const __mpz_struct (&)[1], const myDatatype&)’ must be a nonstatic member function
void operator=(const mpz_t &a, const myDatatype &b);

I read that "A binary operator shall be implemented either by a non-static member function with one parameter or by a non-member function with two parameters", which is what I am doing, I think. How can I solve this?

fc67
  • 409
  • 5
  • 17
  • 3
    `A binary operator shall be implemented either by a non-static member function with one parameter or by a non-member function with two parameters` This doesn't apply to `operator=`. As the compiler correctly notes, `operator=` must be a non-static member function. "Normal" binary operators are usually symmetrical - you generally want both `myObj + 42` and `42 + myObj` to work. But assignment isn't - `myObj = 42;` makes sense, but `42 = myObj` not so much. – Igor Tandetnik Apr 10 '15 at 13:38
  • From the given use case it seems you really want to implement an `mpz_t` constructor that takes a `const myDatatype&`. – Henrik Apr 10 '15 at 13:39
  • @IgorTandetnik Ok, thanks. Then, I'll have to implement this as a function, I guess. – fc67 Apr 10 '15 at 13:41
  • @Henrik Yes, that's what I want to do, but I can't change the mpz_t class for that, so I tried to implement this in my class as an operator. – fc67 Apr 10 '15 at 13:44
  • possible duplicate of [What does "operator = must be a non-static member" mean?](http://stackoverflow.com/questions/871264/what-does-operator-must-be-a-non-static-member-mean) – timrau Apr 10 '15 at 13:44

1 Answers1

2
void operator=(const mpz_t &a, const myDatatype &b);

This is invalid. operator= must be a nonstatic member function as the compiler said.

If mpz_t is external type (that you can't modify), the best option is to define conversion operator:

class myDatatype
{
public:
    operator mpz_t() const
    {
        //return mpz_t object constructed from *this
    }
};

Then, you can use this syntax:

myDatatype my_object = ...;
mpz_t mpz_t_object = my_object;
Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49