您的位置:首页 > 编程语言 > C语言/C++

C++11新特性总结(枚举+继承+左右值引用+变长模板)

2016-02-25 11:27 211 查看
一、枚举+断言+异常

// C++11的一些新的特性
#include "stdafx.h"
#include <cassert>
using namespace std;
// C++98枚举类型
enum book { c66 = 0x0001, c77 = 0x0002, c88 = 0x0003, c99 = 0x0004 };
// C++11强类型-枚举
enum class bookk { c66 = 0x0001, c77 = 0x0002, c88 = 0x0003, c99 = 0x0004 };
// C++11异常noexcept,如果T会抛出异常,则fun就可以抛异常
void T() noexcept(false) {}
void fun() noexcept(noexcept(T())) {}
// C++11 final可以防止函数被重载,override重载
int main()
{
// C++98断言
assert((c99 - 1) == (c66 | c77 | c88));
// C++11静态断言,编译时进行断言
static_assert((c99-1) == (c66|c77|c88),"assert_error");
return 0;
}


二、简化继承

// C++11的一些新的特性
#include "stdafx.h"
#include <iostream>
using namespace std;
// 继承构造函数:通过using,B继承了A中的所有构造函数
struct A {
A(int i) {};
A(double d,int i) {};
A(float f,int i,const char * c) {};
};
struct B :A {
using A::A;
virtual void ExtraInterface() {};
};
// 委派构造函数:
class Info {
public:
Info():Info(1,'a') { }
Info(int i) :Info(i, 'a') { }
Info(char e) :Info(1, e) { }
private:
Info(int i, char e) :type(i), name(e) {}
int type;
char name;
};

int main()
{
return 0;
}

三、移动语义、左值与右值

// C++11的一些新的特性
#include "stdafx.h"
#include <iostream>
using namespace std;
class myc {
public:
myc() :d(5) { cout << "我是空构造" << endl; }
myc(myc && h) :d(h.d) { cout << "我是移动构造" << endl; }
int d;

};
int main()
{
// lambda 函数返回右值,原本此右值生命已结束
auto ReturnRvalue = [=]()->int { return 1 + 2; };
// 通过右值引用&&,右值又具有了生命
int && a = ReturnRvalue();
/*
如何分辨左值与右值:
1、可以取地址&的是左值,无法取地址的是右值
2、将亡值和纯右值是右值,有名字的为左值
注:无法将右值引用绑定给左值,同时,无法将左值引用绑定给右值
*/
cout << a << endl;
myc t;
t.d = 5;
// move强制把左值转化成右值
myc c(move(t));
cout << c.d << endl;
return 0;
}


四、变长模板

// C++11的一些新的特性
#include "stdafx.h"
#include <iostream>
// 引入c语言的参数类型...
#include <cstdarg>
// 引入C++11变长模板
#include <tuple>
using namespace std;
// 定义一个变长参数的函数
double nonconstfunc(int count,...) {
// 声明一个参数列表结构变量
va_list ap;
double sum = 0;
// 开始获取参数,并传入制定的参数个数
va_start(ap,count);
double temp;
for (int i = 0;i < count;++i)
{
temp = va_arg(ap, double);
cout << temp << endl;
// 依次取double型的参数
sum += temp;
}
// 结束
va_end(ap);
return sum;
}
int main()
{
// 常量表达式,编译期间就能确定是常量
constexpr int i = 1;
cout << i << endl;
// 变长函数,隐患是参数类型不一致,就出错
printf("%f\n", nonconstfunc(3, 1.1f, 2.0f, 3.3f));
// C++11引入了变长模板tuple,参数变长,返回值也变长
auto tp = make_tuple(3,"hello",'W');
auto tempFunc = [=]()->tuple<int,const char*> {
cout << get<0>(tp) << get<1>(tp) << get<2>(tp) << endl;
return make_tuple(get<0>(tp), get<1>(tp));
};
auto t = tempFunc();
cout << get<1>(t) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: