1 #include <iostream> 2 #include<string> 3 using namespace std; 4 5 class Point { 6 public: 7 Point(int a, int b) :x(a), y(b) {}; 8 //Point(Point& p) :x(p.x), y(p.y) {}; 9 int getX() { return x; } 10 int getY() { return y; } 11 void print() { 12 cout << "x: " << x << endl << "y: " << y << endl; 13 } 14 private: 15 int x, y; 16 }; 17 18 Point re_Ponit(int a,int b) { 19 Point res(a, b); //創建的是局部變量 20 return res; //傳遞對象實體 21 } 22 23 Point& re_PonitReference1(int a, int b) { 24 Point res(a, b); //創建的是局部變量 25 return res; //傳遞對象引用(類似指針) 26 } 27 28 Point& re_PonitReference2(int a, int b) { 29 Point* res = new Point(a, b); //動態內存分配 30 return *res; //傳遞對象引用 31 } 32 33 34 int main() 35 { 36 Point a1 = re_Ponit(1, 2); //復制構造 37 Point& a2 = re_PonitReference1(2, 3); //引用賦值(該函數傳遞的是一個局部變量的引用) 38 Point& a3 = re_PonitReference2(2, 3); //引用賦值(該函數傳遞的是一個堆內存變量的引用) 39 a1.print(); //1,2 40 a2.print(); //隨機值 41 a3.print(); //2,3 42 }