C++拷贝构造函数
原创
©著作权归作者所有:来自51CTO博客作者深漂小码哥的原创作品,请联系作者获取转载授权,否则将追究法律责任
#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 line(10);
display(line);
system("pause");
return 0;
}