什么时候要有拷贝构造函数?

1、构造函数时用实例化的对象进行构造

int main()
{
	Student a(10, 2);
	Student b = a; // 拷贝构造,并且要特别注意指针数据成员的赋值,避免出现野指针的情况
}

2、返回临时对象(而不是返回对象的引用)

rmb operator+(const rmb &r, int c)
{
	int x = r.a + c;
	rmb b(x);
	return b;
}

3、类的对象作为参数(而不是对象的引用作为参数)

void search(vector a)
{
	// ......
}

猜你喜欢

转载自blog.csdn.net/Littlsecr/article/details/80724061
今日推荐