C++11新特性体验 January 04, 2014 / C&C++ / apacal / 2009 CLICK / 0 comment 前言 C++11,先前被称作C++0x,是C++的最新正式标准,由C++标准委员会于2011年8月12日公布,并于2011年9月出版。2012年2月28日的国际标准草案(N3376)是最接近于现行标准的草案(编辑上的修正)。此次标准为C++98发布后13年来第一次重大修正。该标准添加了许多简化编程的新特性,大大提高的开发者的开发效率。 正文 序列for循环 序列for循环是一种简化的for循环,可以遍历一组序列,包含各种容器,string,数组,初始化列表以及由begin和end函数定义的序列。 /** * test c++11 for循环 */ int main() { vector vec(10, 5); cout << "for a vector\n"; for (auto a : vec) cout << a << ' '; string ch = "apacalblog"; cout << "\nfor a c++ string\n"; for (auto a : ch) cout << a << ' '; cout << "\nfor a array\n"; int p[] = {1, 2, 3, 4, 5}; for (auto a : p) cout << a << ' '; return 0; } 委托构造函数 在引入C++ 11之前,如果某个类有多个重载的构造函数,且这些构造函数中有一些共同的初始化逻辑,通常都需要再编写一个带参数的初始化函数,然后在这些构造函数中调用这个初始化函数。在C++ 11中,再也不用这么麻烦了。我们可以实现一个最基础的构造函数,其他构造函数都调用这个构造函数。 class Person { public: Person() : Person(0, "not name") {} Person(int age) : Person(age, "not name") {} Person(int page, const string &pname) : age(page), name(pname) { //基础构造函数 cout << name << "'s age is " << age << endl; } private: int age; string name; }; int main() { Person person(); Person person1; Person person2(12); Person person3(22, "apacal"); return 0; } 成员变量初始化 与PHP中的用法一样,可以对成员变量进行就地初始化。 class Person { public: Person() : Person(0, "not name") {} Person(int age) : Person(age, "not name") {} Person(int page, const string &pname) : age(page), name(pname) { cout << name << "'s age is " << age << endl; } Person(int age, string name, bool no) {} void print(ostream &os = cout) { cout << name << "'s age is no " << age << endl; } private: int age = 22; string name = "apacal-qingzhu"; }; int main() { Person person = Person(0, "apacal", true); Person person1; Person person2(12); Person person3(22, "apacal"); person.print(); return 0; } 总结 简单地介绍一下C++11,以后继续使用到的时候在总结。 Continue reading