1. 程式人生 > >C++ 拷貝建構函式程式碼筆記

C++ 拷貝建構函式程式碼筆記

拷貝建構函式是一種特殊的建構函式,它在建立物件時,是使用同一類中之前建立的物件來初始化新建立的物件。拷貝建構函式通常用於:

  • 通過使用另一個同類型的物件來初始化新建立的物件。

  • 複製物件把它作為引數傳遞給函式。

  • 複製物件,並從函式返回這個物件

#include <iostream>
using namespace std;
class Point{
public:
	Point(int xx=0,int yy=0):x(xx),y(yy){}     //建構函式

	~Point(){ };                              //解構函式

    Point(const Point &p);                //複製建構函式

	int getX()const{return x;}

	int getY()const{return y;}

private:
	int x,y;//私有成員
};

Point::Point(const Point &p)
{
	x = p.x;
	y = p.y;
	cout << "複製建構函式呼叫" << endl;
}

//形參作為Point類物件的函式
void fun1(Point p) {cout<< p.getX() << endl;}

//返回類的物件
Point fun2()
{
	Point a(1,2);
	return a;
}

int main()
{

	Point a(8);    //第一個物件A,該過程利用了過載,後面的y預設為0

	Point b(a);      //此時呼叫copy建構函式;情況1,用a初始化b,第一次呼叫copy建構函式

	cout << b.getX() << endl; 

	fun1(b);  //此時呼叫copy建構函式;類的物件在函式中為實參,第二次呼叫copy建構函式

	b = fun2();//此時呼叫copy建構函式;函式返回值為類的物件,第三次呼叫copy建構函式

	cout << b.getX() << endl; 

	return 0;
}
複製建構函式呼叫
8
複製建構函式呼叫
8
1