C++学习笔记之拷贝构造

如若没有拷贝构造函数的时候,系统会自动提供(浅拷贝)一个拷贝构造函数,这样的话,再创造一个新的对象的话,会将类中的数据赋值给新的对象。但是如果类中有指针的话,就会把指针赋给它,但这要就会出现混乱。因此这就引出了拷贝构造函数的自己编写。

#include<iostream>
using namespace std;
class student
{
	int a;
public:
	student()
	{
		a=100;
	}
	void getA()
	{
		cout<<a<<endl;
	}
};
int main()
{
	student stu1;
	student stu2(stu1);//stu2=stu1;//
	st2.getA();
	system("pause");
	return 0;
}

以上数据是浅拷贝,只是数据和数据之间的拷贝而已
拷贝构造:类名(const 类名&引用名);

#include<iostream>
using namespace std;
class stu
{
	char *p;
	public:
	student(char *str)
	{
		p=new char[strlen(str)+1];
		strcpy(p.str);
	}
	void getA()
	{
		cout<<p<<endl;
	}
	student(const student&stu)
	{
		p=new char[strlen(stu.p)+1];
		strcpy(p,stu.p);
	}
};
void test(student stu)
{

}
student text(student stu)
{
	return stu;
}
int main()
{
	student stu1("39-lijimin");
	//text(stu1).getA();//第三种情况,用完就直接释放了,调用析构函数
	//test(stu1);//拷贝构造函数的第二种调用情况
	//stu2=stu1;//创造新的类型,用旧的类型赋值的时候,是要求调用拷贝构造的
}

拷贝构造函数的调用情况:
1,用一个类对象去初始化该类的另一个对象时;
2,如果函数的形参是类的对象,调用函数时进行实参传递时,调用拷贝构造
3,如果一个函数的返回值是类对象,函数调用返回时。

发布了9 篇原创文章 · 获赞 12 · 访问量 287

猜你喜欢

转载自blog.csdn.net/weixin_41946168/article/details/105594725