-3

I tried overloading the += but it get's me an error :

expression must have integral or unscoped enum type

class Sensor{};
class SensorList{
Sensor ** sensors;
};

void main(){
Sensor s1;

SensorList *list = new SensorList();
list += &s1;

}

This is the overloading of += operator

SensorList* operator+=(Sensor * sens){

        SensorList * lista= new SensorList();


    Sensor ** temp = new Sensor*[this->noElem];
    for (int i = 0; i < this->noElem; i++)
        temp[i] = this->senzori[i];

    delete[] this->senzori;

    this->senzori = new Sensor*[this->noElem + 1];
    for (int i = 0; i < this->noElem; i++)
        this->senzori[i] = temp[i];
    this->senzori[this->noElem] = sens;

    this->noElem += 1;

    lista = this;



        return lista;
}

How should I do it? I have to overload the new operator?

Alex Chihaia
  • 103
  • 2
  • 15

1 Answers1

1

However that user defined operator+= of yours is actually defined, both operands of

list += &s1;

are pointers. So this will never call a user defined operator as none of the operands is a class or enum type. You just cannot overload any operators for two pointers because of language rules.

Instead it tries to add something to a pointer, and that only works for integrals and enums, as the compiler tells you.

In particular, your problem has nothing to do with operator new, and you apparently did not even try to overload that.


So what to do instead: Stop doing everything through pointers and just overload your operators for the class or references to the class instead. Then you will get something like this:

Sensor s1;
SensorList sl;
sl += s1;

I recommend you read this.

If you really feel the need to use pointers (you probably shouldn't), use a free function like

void add(SensorList*, Sensor*);
Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
  • I've also tried overloading += outside the class and take the first parameter as a pointer to the class type but i get an error saying that at least one parameter must have the class type. I understand what you are telling me, but it's there any solution? If i right `*list += &s1`? – Alex Chihaia Feb 06 '16 at 16:14
  • @AlexChihaia No. As I wrote in my answer, at least one operand of a user defined operator needs to be of class or enum type. You cannot overload an operator for pointers only in C++. – Baum mit Augen Feb 06 '16 at 16:15