C++11/C++14 (五)STATIC ASSERTIONS AND CONSTRUCTOR DELEGATION

来源:互联网 发布:今天移动网络怎么了 编辑:程序博客网 时间:2024/05/21 08:37

PS:以下代码在VS2015编译通过~~~

1. Static assertions 在程序编译期间进行断言判断

The static_assert declaration tests a software assertion at compile time. This can be especially useful for template code.

syntax looks like this:

static_assert{bool_constexpr, string}

举例如下:

       //run-time assert
char* ptr = "hello";
assert(ptr != NULL);


// compile-time assert
static_assert(sizeof(void*) == 4, "64-bit is not supported");

         编译错误1 error C2338: 64-bit is not supported


2.Constructor delegation

c++03中,一个类的构造函数是不能调用其他类的构造函数,必须自己构造类成员或调用成员方法。

请注意,在c++ 03中,类的非常量数据成员不能在这些成员声明的站点上初始化。它们只能在构造函数中初始化。在c++ 11中,现在是允许的.

举例如下:
//c++03 
class A
{
void init(){ cout << "init()" << endl; }
void dosomething(){ cout << "dosomething()" << endl; }
public:
A(){ init(); }
A(int a){ init(); dosomething(); }
};


//c++11
class B
{
int b = 99;
void dosomething(){ cout << "dosomething()" << endl; }
public:
B(){}
B(int b) :B(){ dosomething(); }
};

Copy constructor using constructor delegation
A(const A& b) : A(){  m_a = b.m_a;}