程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> C++11新特性之 Static assertions 和constructor delegation

C++11新特性之 Static assertions 和constructor delegation

編輯:C++入門知識

C++11新特性之 Static assertions 和constructor delegation


C++11新特性繼續。
Static assertion
static_assert 是在編譯時期的斷言,作用不言而喻的。
語法是這樣:

static_assert ( bool_constexpr , string )   

其中:
bool_constexpr: 常量表達式
string: 如果bool_constexpr表達式為false, 這個string就是編譯時候報的錯誤。

看看代碼:

// run-time assert
assert(ptr != NULL)

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

Constructor delegation
之前我們知道,一個類的構造函數不可以調用這個類的其他構造函數。每個構造函數只能包含類的成員變量和共有函數。

// C++03
class A
{
    void init() { std::cout << init(); }
    void doSomethingElse() { std::cout << doSomethingElse()
; }
public:
    A() { init(); }
    A(int a) { init(); doSomethingElse(); }
};

但是C++11允許我們這麼干!

// C++11
class A
{
    void doSomethingElse() { std::cout << doSomethingElse()
; }
public:
    A() { ... }
    A(int a) : A() { doSomethingElse(); }
};

然後,此時此刻應該有個警告:
wiki :
C++03 considers an object to be constructed when its constructor finishes executing, but C++11 considers an object constructed once any constructor finishes execution. Since multiple constructors will be allowed to execute, this will mean that each delegating constructor will be executing on a fully constructed object of its own type. Derived class constructors will execute after all delegation in their base classes is complete.

For base-class constructors, C++11 allows a class to specify that base class constructors will be inherited. This means that the C++11 compiler will generate code to perform the inheritance, the forwarding of the derived class to the base class. Note that this is an all-or-nothing feature; either all of that base class’s constructors are forwarded or none of them are. Also, note that there are restrictions for multiple inheritance, such that class constructors cannot be inherited from two classes that use constructors with the same signature. Nor can a constructor in the derived class exist that matches a signature in the inherited base class.

Note that in C++03, non-constant data members of classes cannot be initialized at the site of the declaration of those members. They can be initialized only in a constructor. In C++11, now it’s allowed:

// C++11
class A
{
    int a = 99
    void doSomethingElse() { std::cout << doSomethingElse()
; }
public:
    A() { ... }
    A(int a) : A() { doSomethingElse(); }
};

拷貝構造函數使用constructor delegation

A(const A& b) : A()
{
  m_a = b.m_a;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved