C++拷貝建構函式 的理解
阿新 • • 發佈:2018-11-25
#include <iostream> using namespace std; //拷貝建構函式的理解 class Point { public: Point(); Point(int X, int Y); ~Point(); Point(Point &p); void setPoint(int X, int Y) { x = X; y = Y; } public: int x, y; }; Point::Point() { x = 0; y = 0; cout<< "預設樣式的建構函式\n"; } Point::Point(int X, int Y) { x = X; y = Y; cout << "正常構造\n"; } Point::~Point() { cout << "點(" << x << "," << y << ")解構函式呼叫完畢\n"; } Point::Point(Point &p) { x = p.x; y = p.y; cout << "拷貝建構函式\n"; } voidf(Point p) { cout << "函式f之中:" << endl; p.setPoint(p.x, p.y); } void f2(Point &p) { cout << "函式f之中:" << endl; p.setPoint(p.x, p.y); } Point g() { Point a(7, 33); cout << "函式g之中:" << endl; return a; } int main(void) { Point p1(10, 10); Point p2; f(p2); f2(p1); return 0; } /*總結: 1.對於f()函式的呼叫,首先要“呼叫拷貝建構函式”以實現從實參到形參的傳遞 相當於語句 “形參 = 實參”(p = p2),當函式型別為引用時,就不會呼叫拷貝建構函式。 引用相當於別名 不申請記憶體空間. 2.對於建構函式和解構函式的呼叫時一一對應的,即“先構造的後析構”類似於棧的“先進後出”原則。 */