1.初始化变量:
int i1 = 7.2;//正确,但是i1的值变为了7
int i{ 7 };//建议使用初始值列表
//int i2{ 7.2 };//错误:初始值列表确保不会发生某些可能导致信息丢失的类型转换
//int i3 = { 7.2 };//错误:同上,且=是多余的
2.使用auto关键字:
struct Record {
string name;
int id;
};
auto p = new Record{ "Hume", 110 };
cout << p->name << "\t" << p->id << endl;
delete p;
int v[]{ 10, 20, 30, 40, 50 };
for (int& num : v)
{
cout << num++ << "\t";
}
cout << "\n";
for (auto i = 0; i < sizeof(v) / sizeof(int); i++)
{
cout << v[i] << "\t";
}
cout << "\n";
auto根据值识别变量的类型。
3.将指针指向空指针:
char* p1 = nullptr;
char* p2 = NULL;
char* p3 = 0;
if (p1 == p2 && p1 == p3)
{
cout << "YES!" << endl;//YES
}
建议使用nullptr