Hilfestellung bei der Operatorüberladung
-
Hey Leute,
Habe heute mal Operatorüberladung gemacht und soweit funktioniert das auch alles. Nun frage ich mich wie man dafür sorgen kann, dass folgendes in der Main geschrieben werden kann:
test[1] = 7;#include <iostream> class Element{ public: Element *next; int value; Element(int inputValue){ this->value = inputValue; this->next = nullptr; } }; class Liste{ public: Element *start; Element *last; Liste(int val = 0){ start = 0; last = 0; int i; for(i=0; i<val; i++){ push(0); } } ~Liste(){ if(start != nullptr && last != nullptr){ Element *temp = 0; while(start != nullptr){ temp = start; start = temp->next; delete temp; } } } void push(int a){ Element *temp = new Element(a); if(start == 0){ start = temp; last = temp; } else{ last->next = temp; last = temp; } } void rep(int position, int reValue){ int i; Element *pos = start; for(i=0;i < position; i++){ if(pos == nullptr){ std::cout << "OUT OF BOUNDS"; }else{ pos = pos->next; } } if(pos == nullptr){ std::cout << "OUT OF BOUNDS" << std::endl; return; } pos->value = reValue; } int getAt(int position){ int i; Element *pos = start; for(i=0; pos != last && i < position; i++){ pos = pos->next; } if(pos == 0){ std::cout << "OUT OF BOUNDS" << std::endl; exit; } return pos->value; } int operator[](const int &x){ return getAt(x); } }; int main(){ int i; Liste test(3); for(i=0; i<3; i++){ std::cout << test.getAt(i) << std::endl; } test.rep(0,3); test.rep(1,2); test.rep(2,1); for(i=0; i<3; i++){ std::cout << test.getAt(i) << std::endl; } test.push(5); for(i=0; i<4; i++){ std::cout << test[i] << std::endl; } return 0; }Schonmal Danke für eure Hilfe

-
Dazu muss dein
operator[]eine Referenz zurück geben. Und als Parameter hätte ich auch einen normalen int genommen statt const reference, deine getAt Funktion hat ja auch int als Parameter. Wenn du es so schreibst sollteste es gehen:int& getAt(int position) int& operator[](int x) // Eventuell zusätzlich noch die const Variante davon const int& getAt(int position) const const int& operator[](int x) const
-
aah, danke.
Auf die Lösung hätte ich selber kommen müssen XD
