C++静态成员

来源:互联网 发布:淘宝店铺客服几点上班 编辑:程序博客网 时间:2024/05/16 12:21

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 expressionstatic const char name[nameSize];};// cppconst 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),而对指针所指的对象无关。


0 0