花费一星期学习了一下c++11,重看c++ prime感觉第五版的例子比第四版好了很多呀。而且还加入了设计模式之类的东西。也或许是之前看的时候还不知道什么是设计模式T_T。
写了一写测试代码,记录一下以备后用。
使用auto和decltype自动推倒类型:
注意事项见源码中注释
#include <iostream>
using namespace std;
int f() {
return 10;
}
int main(int argc, char* argv[]) {
int i = 0;
const int a = i, &b = a;
auto x = a; //int 类型 去掉顶层const
x = 10;
auto c = b; //b是a的别名,a为int,所以c也为int
c = x;
cout << i << " " << a << " " << b << " " << x << " " << c << endl;
//0 0 0 10 10
const auto d = a; //显示const
cout << a << endl;
//d = 10;
const int aa = i, &bb = aa;
decltype(aa) xx = aa; //const int
decltype(bb) yy = bb; // const int &, 引用只有在decltype处不是变量的别名
//yy = 10;
cout << aa << " " << bb << " " << xx << " " << yy << endl;
decltype(i) nn = i;
decltype((i)) mm = i; //双括号为引用
mm = 100;
cout << nn << " " << mm << endl;
//0 100
decltype(f()) aaa; //int
aaa = 10;
cout << aaa << endl;
cout << "Hello world!" << endl;
return 0;
}
成员变量的类内值初始化
#include <iostream>
using namespace std;
class A {
int a = 10;
public:
void show() const {
cout << a << endl;
}
};
int main(int argc, char* argv[]){
A a;
a.show();
cout << "Hello world!" << endl;
return 0;
}
容器的大括号初始化;range for语句;数组的begin end函数;除法向零取整
#include <iostream>
#include <vector>
#include <iterator>
using namespace std;
class A {
public:
int a, b;
virtual ~A(){
}
};
int main(int argc, char* argv[]) {
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v = {1, 2, 3/*, 4.0*/}; //double占8字节 int 4字节,大空间到小空间不允许
for(auto& x : v) {
x += 10;
}
for(auto& x : v) {
cout << x << endl;
}
int p[] = {1, 2, 3, -4};
int* s = begin(p);
int* e = end(p);
while(s != e && *s > 0)
++s;
if(s == e) {
cout << "no" << endl;
} else {
cout << *s << endl;
}
int a = 10;
int b = -3;
int c = 3;
cout << a / b << " " << a / c << endl; //向0取整
//-3 3
cout << sizeof(A) << " " << sizeof A::a << endl;
cout << "Hello world!" << endl;
return 0;
}