C++开发初级


794 浏览 5 years, 3 months

3.1.8 类内成员初始化器(仅限C++11)

版权声明: 转载请注明出处 http://www.codingsoho.com/
类内成员初始化器(In-Class Member Initializer)(仅限C++11)

C++11允许在定义类的时候直接初始化成员变量。例如:

#include <string>
class MyClass
{
  protected:
    int mInt = 1;
    std::string mStr = "test";
}

值存在代码段中,符号表

在C++11之前,只有在构造函数体或ctorinitializer中才能初始化mInt和mStr,如下所示:

#include <string>
class MyClass
{
  public:
    MyClass() : mInt(1), mStr("test") {}
  protected:
    int mInt;
    std::string mStr;
}

在C++11之前,只有static const整型成员变量才能在类定义中初始化,例如:

static const 放在全局数据段

#include <string>
class MyClass
{
  protected:
    static const int kI1 = 1; //OK
    static const std:string kStr = "test"; //Error:  not integral type
    static int sI2 = 1; // Error: not const
    const int kI3 = 3; // Error: not static
}