C++靜態成員

we can provide in-class initializers for static members that have const integral

type and must do so for static members that are constexprs of literal type.The initializers must be constant expressions.
黑色字體我翻譯成:用常量表達式初始化的字面值類型的constexpr靜態成員也可以爲其提供類內初始值。

這裏的literal type,指在編譯時就能計算得到的,一般,算數類型、引用和指針都屬於字面值類型。

int ival = 10;
class Test
{
    static constexpr int &_ival = ival;
};

通常靜態數據成員在類聲明中聲明,在包含類方法的文件中初始化.初始化時使用作用域操作符來指出靜態成員所屬的類.

類內初始化,必須在cpp中再次定義,但是因爲這個靜態數據成員的初始值是在類體中指定的, 所以在類定義之外的定義不能指定初始值。

1. 在類中,只是聲明瞭靜態變量,並沒有定義。 2. 聲明只是表明了變量的數據類型和屬性,並不分配內存;定義則是需要分配內存的。

// 頭文件
class Account {
// ...
private:
static const int nameSize = 16;//好像vc下不支持這樣, const expression
static const char name[nameSize];
};
// cpp
const int Account::nameSize;// 必需的成員定義

const char Account::name[nameSize]="Savings Account";


被聲明爲constexpr的對象是一個隱式的const,而constexpr最大的作用是去驗證所聲明的變量是不是一個常量表達式。

variables defined inside a function ordinarily are not stored at a fixed address. Hence, we cannot use a constexpr
pointer to point to such variables. On the other hand, the address of an object defined outside of any function is a constant expression, and so may be used to initialize a constexpr pointer.

我們可以用全局性的對象的地址來初始化constexpr對象,也可用全局性的對象來綁定constexpr引用。

constexpr僅僅對指針有效(也就是將指針隱式定義爲const),而對指針所指的對象無關。


發佈了1 篇原創文章 · 獲贊 0 · 訪問量 8025
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章