基本类型的显式初始化-C++

12 篇文章 0 订阅

如果采用不含参数的、明确的构造函数调用语法,基本型别会被初始化为

#include<iostream>
using namespace std;
int main()
{
	int a = int();
	float b = float();
	double c = double();
	string d = string();
	char e = char();
	cout << a << endl;//0
	cout << b << endl;//0
	cout << c << endl;//0
	cout << d << endl;//""
	cout << e << endl;//'\0'
	return 0;
}

基本数据型别提供有default构造函数,以为初值。

#include<unordered_map>
#include<iostream>
using namespace std;
int main()
{
	unordered_map<int, int>ump;
	int n = 10;
	while (n--)
	{
		ump[n];
	}
	for (pair<int, int>u : ump)
	{
		cout << u.first << " " << u.second << endl;
	}
	return 0;
}
9 0
8 0
7 0
6 0
5 0
4 0
3 0
2 0
1 0
0 0

使用default构造函数与删除default构造函数

#include<iostream>
using namespace std;
class noedn1
{
public:
	noedn1() = default;
	noedn1(int);
};
noedn1::noedn1(int) { cout << "1: construct function." << endl; }
class noedn2
{
public:
	noedn2() = delete;
	noedn2(int);
};
noedn2::noedn2(int) { cout << "2: construct function." << endl; }
int main()
{
	noedn1 a1;
	noedn1 a2(0);//1: construct function.
	//noedn2 b1;//error: 尝试引用已删除的函数
	noedn2 b2(0);//2: construct function.
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值