1一個對象調(diào)用另一個對象時候調(diào)用拷貝構(gòu)造函數(shù) 源代碼:#include<iostream> using namespace std; class Point{ private: int x,y; public: Point(int x,int y){this->x=x;this->y=y;} Point(Point& p){ this->x=p.x; this->y=p.y; cout<<"拷貝構(gòu)造函數(shù)被調(diào)用!"<<endl; } int Getx(){return x;} int Gety(){return y;} }; int main(){ Point A(1,2); Point B(A); cout<<B.Gety()<<endl; } ![]() 2當函數(shù)的參數(shù)是一個類 類型時 調(diào)用拷貝構(gòu)造函數(shù) 源代碼2: #include<iostream> using namespace std; class Point{ private: int x,y; public: Point(int x,int y){this->x=x;this->y=y;} Point(Point& p){ this->x=p.x; this->y=p.y; cout<<"拷貝構(gòu)造函數(shù)被調(diào)用!"<<endl; } int Getx(){return x;} int Gety(){return y;} }; int func1(Point p){ cout<<p.Getx()<<endl; } int main(){ Point A(1,2); func1(A); } ![]() 3當函數(shù)的返回值類型是類 類型時 調(diào)用構(gòu)造函數(shù) ... #include<iostream> using namespace std; class Point{ private: int x,y; public: Point(int x,int y){this->x=x;this->y=y;} Point(Point& p){//拷貝構(gòu)造函數(shù) this->x=p.x; this->y=p.y; cout<<"拷貝構(gòu)造函數(shù)被調(diào)用!"<<endl; } int Getx(){return x;} int Gety(){return y;} }; int func1(Point p){ cout<<p.Getx()<<endl; } Point func2(){ Point A1(12,23); return A1;//調(diào)用拷貝構(gòu)造函數(shù) } int main(){ Point B=func2(); cout<<B.Getx()<<endl; } |
|