再谈构造函数

创建一个类,一定要调用构造函数,那么构造函数包括哪些种类呢?

默认构造函数

没有定义构造函数时使用,默认构造函数

  • 默认无参构造函数,函数体为空,什么内容都没有
  • 默认拷贝构造函数,注意:当没有自定义拷贝构造函数时,使用拷贝构造是调用,默认的拷贝构造函数可以进行简单的赋值。(所有会出现浅拷贝)

默认无参构造大家都很了解,那默认拷贝构造呢?
请看下面例子,自定义了无参构造,只剩下了默认拷贝构造

class A{
public:
	A(){
		cout << "create A" << endl;
	}
	int a;
};
void test()
{
	A a1;
	A a2(a1);
	A a3 = a2;
}
int main()
{
	test();
	system("pause");
	return 0;
}

输出结果只有一次crate A
说明 A a2(a1); A a3 = a2;是拷贝构造。
注意 : A a3 = a2 和 a3 = a2 是两个完全不同的概念一个是调用拷贝构造函数,一个是操作符运算,通过对操作符=重载可以看出

class A{
public:
	A():a(10){
		cout << "A()create A" << endl;
	}
	A(const A& other){
		this->a = other.a; 
		cout << "A(const A& other) create A" << endl;
	}
	A& operator=(const A&other){
		cout << "A& operator=(const A&other) " << endl;
		this->a = other.a;
		return *this;
	}
	int a;
};
void test()
{
	A a2;
	A a3 = a2;
	a3 = a2;
}
int main()
{
	test();
	system("pause");
	return 0;
}

结果如下:
A()create A
A(const A& other) create A
A& operator=(const A&other)
再来说说构造函数的种类

构造函数的种类

实际上一共就只有这四种(更准确的说只有三种),注意构造函数可以是可以重载的。

  • 无参构造
  • 有参构造
  • 拷贝构造
  • 默认构造
发布了145 篇原创文章 · 获赞 12 · 访问量 9658

猜你喜欢

转载自blog.csdn.net/weixin_44997886/article/details/104595438