C++ 11语法甜点1 C++ 11中引入了许多简化编程工作的语法上的新特性,我们暂且美其名曰“语法甜点”。下面一一进行介绍。 1 vector<int> vctTemp{1, 2, 3};
2 for (auto a : vctTemp) 3 { 4 cout << a << endl; 5 }
语法甜点2:委托构造函数 1 class CPerson
2 { 3 public: 4 CPerson() : CPerson(0, "") { NULL; } 5 CPerson(int nAge) : CPerson(nAge, "") { NULL; } 6 CPerson(int nAge, const string &strName) 7 { 8 stringstream ss; 9 ss << strName << "is " << nAge << "years old."; 10 m_strInfo = ss.str(); 11 } 12 13 private: 14 string m_strInfo; 15 };
语法甜点3:统一的初始化语法 1 int a{5};
2 char c{'X'}; 3 int p[5] = {1, 2,3, 4, 5}; 4 vector<int> vctTemp{1, 2, 3}; 5 CPerson person{10, "Mike"}; 6 int b = 5.3; // b赋值成5,发生了窄转换 7 int d{5.3}; // 会提示编译错误,避免了窄转换
语法甜点4:nullptr 1 void F(int a)
2 { 3 cout << a << endl; 4 } 5 6 void F(char *p) 7 { 8 assert(p != NULL); 9 10 cout << p << endl; 11 } 12 13 int main(int argc, _TCHAR* argv[]) 14 { 15 int *p = nullptr; 16 int *q = NULL; 17 bool bEqual = (p == q); // 两个指针值是相等的,bEqual为true 18 int a = nullptr; // 编译失败,nullptr不是转换为int 19 20 F(0); // 在C++ 98中编译失败,有二义性;在C++ 11中调用F(int) 21 F(nullptr); // 调用F(char *) 22 23 getchar(); 24 return 0; 25 }
语法甜点5:成员变量初始化 1 class CPerson
2 { 3 private: 4 int m_nAge = 10; 5 string m_strName = "Mike"; 6 };
语法甜点6:默认或禁用函数 1 class CPerson
2 { 3 public: 4 CPerson() = default; 5 CPerson(const CPerson &person) = delete; 6 };
语法甜点7:继承的构造函数 1 class CBase
2 { 3 }; 4 5 class CDerived : public CBase 6 { 7 public: 8 using CBase::CBase; 9 CDerived(int nData) : m_nData(nData) { NULL; } 10 11 private: 12 int m_nData = 10; 13 };
语法甜点8:模板右边双括号
语法甜点9:static_assert 1 char a = 10;
2 static_assert(sizeof(a)==4, "a is not an integer.");
语法甜点10:初始化列表 1 void Print(const initializer_list<int> &ilData)
2 { 3 for (auto a : ilData) 4 { 5 cout << a << endl; 6 } 7 } 8 9 int main(int argc, _TCHAR* argv[]) 10 { 11 vector<int> vctNum = {1, 2, 3, 4, 5}; 12 map<string, string> mapID2Name = {{"92001", "Jack"}, {"92002", "Mike"}}; 13 string strText{"hello world"}; 14 Print({}); 15 Print({1, 2}); 16 Print({1, 2, 3, 4, 5}); 17 18 getchar(); 19 return 0; 20 } 标签: C++ 11 |
|