Copy structure of C ++ study notes

If there is no copy constructor, the system will automatically provide (shallow copy) a copy constructor. In this case, if a new object is created, the data in the class will be assigned to the new object. But if there is a pointer in the class, the pointer will be assigned to it, but this will cause confusion. So this leads to the self-writing of the copy constructor.

#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;
}

The above data is a shallow copy, just a copy between data and data.
Copy structure: class name (const class name & reference name);

#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;//创造新的类型,用旧的类型赋值的时候,是要求调用拷贝构造的
}

Copy constructor call situation:
1. When a class object is used to initialize another object of the class;
2. If the formal parameter of the function is an object of the class, when the actual parameter is passed when the function is called, the copy construction is called
3. If The return value of a function is a class object, when the function call returns.

Published 9 original articles · won 12 · views 287

Guess you like

Origin blog.csdn.net/weixin_41946168/article/details/105594725