#include<iostream>
using namespace std;
class Line
{
public :
int getLength(void);
Line(int len);
Line(const Line &obj);
~Line();
private:
int *ptr;
};
//成員函數定義
Line::Line(int len)
{
cout << "調用構造函數" << endl;
ptr = new int;//爲指針分配內存
*ptr = len;
}
Line::Line(const Line &obj)
{
cout << "調用拷貝構造函數併爲指針ptr分配內存" << endl;
ptr = new int;
*ptr = *obj.ptr;//拷貝值
}
Line::~Line(void)
{
cout << "釋放內存" << endl;
delete ptr;//釋放內存
}
int Line::getLength(void) {
return *ptr;
}
void display(Line obj)
{
cout << "line大小:" << obj.getLength() << endl;
}
int main()
{
Line line1(10);
Line line2 = line1;//調用拷貝構造函數
display(line1);
display(line2);
return 0;
}
c++——拷貝構造函數
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.