+ operator überladen
-
Hab mich über noch ein ähnliche Klasse gestürzt...
Hier gehts auch hauptsächlich ums Überladen von Operatoren...Würd gern wissen, ob die klasse stimmt, also ob grobe fehler drinnen sind..
class Fahrrad { public: std::string sponsor; std::string farbe; double kmstand; bool defekt; public: void print(); void unfall(); void reparatur(); Fahrrad(string spons); Fahrrad(string spons, string f); Fahrrad(string spons, string f, bool is_defekt); Fahrrad operator+=(const Fahrrad& f2) { kmstand+=f2.kmstand; return *this; } ~Fahrrad(); }; Fahrrad::Fahrrad(string spons) { sponsor=spons; } Fahrrad::Fahrrad(string spons, string f) { sponsor=spons; farbe=f; } Fahrrad::Fahrrad(string spons, string f, bool isdefekt) { sponsor=spons; farbe=f; defekt=isdefekt; } void Fahrrad::print() { cout << "Sponsor: " << sponsor <<endl; cout << "Farbe: " << farbe<<endl; if (defekt) cout <<"kaput"<<endl; } void Fahrrad::reparatur() { kmstand = 0; //nach der Reparatur wird kmstand auf 0 gesetzt } const Fahrrad operator+(Fahrrad f1, const Fahrrad& f2) { return f1+=f2; }
hab nur ein problem:
der kilometerstand soll nur dann erhöht werden, wenn das fahrrad
funktionstüchtig ist...im konstrukter kennt er das bool isdefekt ja leider
nicht...deshalb weiß ich nicht, wie ich die überprüfung machen soll..weiß das jemand?
noch eine zweite Frage:
bei einer zahl zb 18,45 ...wie komme ich zu den ,45?
-
void reparatur();
Das ist zwar eine reine Stillfrage allerdings tut ein Objekt ja was wenn eine Methode aufgerufen wird. Also wird man es eher mit einem Verb als mit einem Dingwort in Verbindung bringen.
Fahrrad operator+=(const Fahrrad& f2) { kmstand+=f2.kmstand; return *this; }
Du solltest eine non const Reference zurückgeben. Wie sollen sonst solche Konstrukte funktioniren:
a+=b+=c;
Fahrrad(string spons); Fahrrad(string spons, string f); Fahrrad(string spons, string f, bool is_defekt);
Mach daraus mal
Fahrrad(string spons, string f="", bool is_defekt=false);
Und dann wirfst du die Definitionen für Fahrrad(string spons); und Fahrrad(string spons, string f); weg. Wichtig die default Werte für die Parameter nicht in der Definition wiederholen.
~Fahrrad();
Ziemlich überflüssig nicht?
-
dein problem mit dem überladenen operator:
du willst quasi a=a+b; "rechnen"
also in der Deklaration (auszug):
float wert;
betrag operator+(const betrag &rhs);
betrag operator=(const betrag &rhs);
//konstruktor
betrag(const float &rhs);
betrag(const betrag &rhs);Definition:
betrag betrag::operator+(const betrag &rhs)
{
return(betrag(wert+rhs.wert));
}
betrag betrag::operator=(const betrag &rhs)
{
wert=rhs.wert;
return(betrag(rhs));
}betrag::betrag(const float &rhs)
{
wert=rhs;
}betrag::betrag(const betrag &rhs)
{
wert=rhs.wert;
}vorteil:
a=b möglich
a=a+b möglich
c=a=a+b auch möglichciao