problem konstruktor aufrufe
-
hallo leute,
wieso gibt der mir bei folgendem programm die bestimmten konstruktor aufrufe aus? kapier ich nun wirklich nicht ..#include <iostream> #include <conio.h> using namespace std; class Punkt{ int x,y; public: Punkt(){x=0; y=0;cout<<"Aufruf Standardkonstruktor"<<endl;} Punkt(int a, int b):x(a),y(b){cout<<"Aufruf Parameterkonstruktor"<<endl;} Punkt(const Punkt &p):x(p.x),y(p.y){cout<<"Aufruf Kopierkonstruktor"<<endl;} Punkt operator+(Punkt pp); friend ostream& operator<<(ostream& os, Punkt p); void drucke(){cout<<x<<","<<y<<endl;} }; Punkt Punkt :: operator+(Punkt pp){ Punkt tmp; tmp.x=x+pp.x; tmp.y=y+pp.y; cout<<"Aufruf +operator!!"<<endl; return tmp; } ostream& operator<<(ostream& out, Punkt p){ out<<"("<<p.x<<","<<p.y<<")"<<endl; return out; } int main(void){ Punkt p1(10,10);//Aufruf Paramterkonstruktor Punkt p2(5,3);//Aufruf Parameterkonstruktor Punkt p3;//Aufruf Standardkonstruktor cout <<"Punkt1: "<<endl; //Aufruf Kopierkonstruktor, wieso? cout <<p1; cout <<"Punkt2: "<<endl; //Aufruf Kopierkonstruktor, wieso? cout <<p2; //Aufruf Kopierkonstruktor, wieso? //Aufruf Standardkonstruktor, wieso? //Aufruf operator+ p3=p1+p2; cout <<"Punkt1 + Punkt2 = "<<endl; //Aufruf Kopierkonstruktor, wieso? cout <<p3; getch(); return 0; }vielen dank schon mal....
greetz
-
Weil du die Punkte als Wert an den Operator übergibtst. Stünde als Parametertyp dort const Punkt& würde der Kopierkonstruktor nicht aufgerufen, da nicht ein neues Objekt, sondern nur eine Referenz auf das übergebene Objekt erstellt wird.
-
könntest du mir dafür ein beispiel geben, hab das leider so nicht verstanden, danke!
-
So muss es heißen:
//Jetzt nimmst du eine konstante Referenz auf einen Punkt anstatt eine Kopie des Objekts ostream& operator<<(ostream& out, const Punkt &p){ out<<"("<<p.x<<","<<p.y<<")"<<endl; return out; }
-
void fun (int objekt) { objekt = 42; } void fun2 (int& referenz) { objekt = 42; } int main () { int i = 10; fun (i); // i wird nach objekt kopiert, objekt wird 42 zugewiesen, hat aber keine Auswirkungen auf i fun2 (i); // Die Adresse von i wird nach referenz kopiert, die Zuweisung betrifft also auch i }
-
upps, das hatte ich jetzt total übersehen. peinlich!!! alles klar, trotzdem danke!!!
feierabend für heute ...