0

I need to do a Linked List and overloading the '+' operator in C++. I read some articles like this , but no success. Basically, I have a simple class like above, but actually a take this error: invalid operands of types ‘MyList*’ and ‘MyList*’ to binary ‘operator+’

class MyList {
private:
    int value;
    MyList* next;

public:
    MyList(int value);
    ~MyList();

    MyList* operator+(MyList* list){
        return new MyList(this->value + list->value);
    }

};

MyList::MyList(int value) {
    this->next = NULL;
    this->value = value;
}
MyList::~MyList() {
    cout << "Destroy" << endl;
}

int main() {

    MyList *list1 = new MyList(5);
    MyList* list2 = new MyList(2);
    MyList* result = list1 + list2; //here this error: invalid operands of types ‘MyList*’ and ‘MyList*’ to binary ‘operator+’
    cout << result;

    delete list1;
    delete list2;
    delete result;

    return 0;
}

Any suggestions?

Community
  • 1
  • 1
Rafael
  • 167
  • 1
  • 1
  • 7
  • 1
    Please stop using so many pointers for your own sake. Your `main` should look a lot simpler: `MyList list1(5); MyList list2(2); MyList result = list1 + list2; std::cout << result;` – chris Apr 13 '14 at 18:13
  • That MyList class looks more like a Node class to me. – Rad1 Apr 13 '14 at 18:16
  • You shouldn't add operator+ for that. You should have a get function for the int. – Neil Kirk Apr 13 '14 at 18:23
  • @chris unhappily, your suggestion didn't work. error: no match for ‘operator+’ in ‘list1 + list2’ in line: MyList result = list1 + list2; – Rafael Apr 13 '14 at 19:36
  • @user3529544, You should overload `operator+` using a normal signature so that it does work. See [operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading). Overloading it to operate on pointers is asking for trouble. – chris Apr 13 '14 at 19:39

2 Answers2

0

You need to use references, not pointers.
Anyway, you seem to have pointerities, an unhealthy love of pointers. Use some proper values instead of using dynamic allocation.
Historically, references were introduced for operator overloading btw.

Also, you need to return a new MyList from operator+.

Use member function: MyList operator+(const MyList& list) const

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
0

Define the operator the following way

MyList * operator +( const MyList &list ) const
{
    return new MyList(this->value + list->value);
}

and call it in main as

MyList* result = *list1 + *list2;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335