如果采用不含参数的、明确的构造函数调用语法,基本型别会被初始化为零 :
#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;
cout << b << endl;
cout << c << endl;
cout << d << endl;
cout << e << endl;
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);
noedn2 b2(0);
return 0;
}
|