1,委托构造函数(Delegating Constructor)
class Test{
public:
Test(int n){}
Test() : Test(0) {}
};
//调用构造函数时候,调用其他的构造函数,可以完成一些初始化的工作。
int main{
return 0;
}
2,类内初始化 In-Class Initializer
struct Data{
int i;
float f;
bool b;
Data(): i(0),f(0),b(true) {}
};
C++11 :
struct Data{
int i = 1;
float f = 2.0;
bool b = true;
};
3,空指针
char* s = NULL;
int i = NULL;
float f = NULL;
void func(char* s);
void func(int i);
以上调用可能会导致歧义
建议nullptr赋值替代NULL
4,枚举
enum class Number {One, Two, Three};
Number num = Number::One;
tip:无法赋值给int,int num = Number::One;
5,类型推导
vector<pair<int,int>> numbers = {{1,2},{2,3}};
for(auto it = numbers.cbegin(); it != numbers.cend(); ++it){
cout << it->first << "," << it->second << endl;
}
auto i = 1;
template <typename T, typename U>
auto add2(T x, U y) -> decltype(x+y){
return x+y;
}
//C++14
template <typename T, typename U>
auto add(T x, U y) {
return x+y;
}
cout << add(1,2.0) << endl;
7,constexpr 常量表达式 C++11
constexpr int pow(int x , int y){
int result = x;
while(--y > 0){
return *= x;
}
return result;
}
constexpr int pow(int x, int y){
return y == 0 ? 1:x*pow(x,y-1);
}
int main{
//int a[pow(2,4)] = {};
int a[16] = {}; //constexpr在编译期运行用于性能优化
constexpr int a = (1+2)*3;
constexpr int b = a+3;
return 0;
}
8,初始化列表
std::vector<int> v = {1,2,3};
std::set<int> s = {1,2,3};
std::list<int> l = {2,4,5};
vector<set<int> > v = {{2,3}, {3,3,5} };
9,for
vector<int> nums = {1,2,3};
for (int x : nums){
cout << x << endl;
}
10,C++14
map<int,string> numMap = {{1,"one"}, {2,"Two"}};
for(auto [key,val] : numMap){
cout << key << "->" << val << endl;
}
//old style
for(map<int,string>::iterator it = numMap.begin();it!=numMap.end(); ++it){
cout << it->first << "->" << it->second << endl;
}
11,unique_ptr 智能指针
struct SomeData{
int a,b,c;
};
void f(){
//SomeData* data = new SomeData;
//unique_ptr<SomeData> data(new SomeData);
//or 推荐以下
auto data = make_unique<SomeData>();//SomeData构造抛出异常 也不会得到野指针
data->a=1;
data->b=2;
data->c=3;
}
//一个unique_ptr指向一个对象
//多个指针指向同一个对象/或者指针在函数间传递可用shared_ptr
12,lambda
//#include <algorithm> 算法可参考使用
vector<int> nums = {1,2,3,4};
auto it = find_if(nums.begin(),nums.end(), [](int x) {
return x % 2 == 0;
});
cout << "The first odd number is" << *it;
//现代C++教程书籍可以学习