C++学习之——类与对象(拷贝构造函数 )

[本节内容]

拷贝构造函数

4.1概念

只有单个形参,该形参是对本类类型对象的引用(一般用const修饰),在用已存在的类类型创建新对象时由编译器自动调用

4.2特征

拷贝构造函数也是特殊的成员函数,其特征如下:
1.拷贝构造函数是构造函数的一个重载形式
2.拷贝构造函数的参数只有一个且必须使用引用传参,使用传值方式会引发无穷递归调用。

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	Date(const Date& d)      //类类型对象的引用
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
private:
	int _year;
	int _month;
	int _day;
};


int main()
{
	Date d1;
	Date d2(d1);        //d2是d1拷贝构造的结果
	system("pause");
	return 0;
}

在这里插入图片描述
3.若未显式定义,系统生成默认的拷贝构造函数。默认的拷贝构造函数对象按内存存储按字节节序完成拷贝,这种拷贝我们叫做浅拷贝或值拷贝。

class Date
{
public:
	Date(int year = 1900, int month = 1, int day = 1)
	{
		_year = year;
		_month = month;
		_day = day;
	}
	
private:
	int _year;
	int _month;
	int _day;
};
int main()
{
	Date d1;
	Date d2(d1);
	system("pause");
	return 0;
}

**注意:**默认拷贝构造函数无论是什么类型,都直接按直接进行值拷贝。
但是对string,栈…数据结构中需要开辟空间的类型无法完成拷贝,因为它们要用同一块空间完成拷贝,但无法完成同时释放。

class String
{
public:
	String(const char* str = "jack")
	{
		_str = (char*)malloc(strlen(str) + 1);
		strcpy(_str, str);
	}
	~String
	{
		cout << "~String()" << endl;
		free(_str);
	}
private:
	char* _str;
};

int main()
{
	String s1("hello");
	String s2(s1);       //  程序奔溃且输出两个~String
}

猜你喜欢

转载自blog.csdn.net/ly_6699/article/details/87891332