c++11 学习及测试(auto,decltype,range for...)

花费一星期学习了一下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;
}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值