如何初始化类字段?

时间:2010-07-16 12:01:39

标签: c++ initialization ctor-initializer

一个基本问题,但我很难找到明确的答案。

除了方法中的赋值之外,初始化器是否列出了方法来初始化C ++中的类字段?

如果我使用了错误的术语,这就是我的意思:

class Test
{
public:
    Test(): MyField(47) { }  // acceptable
    int MyField;
};

class Test
{
public:
    int MyField = 47; // invalid: only static const integral data members allowed
};

编辑:特别是,是否有一种使用struct初始化器初始化struct字段的好方法?例如:

struct MyStruct { int Number, const char* Text };

MyStruct struct1 = {};  // acceptable: zeroed
MyStruct struct2 = { 47, "Blah" } // acceptable

class MyClass
{
    MyStruct struct3 = ???  // not acceptable
};

4 个答案:

答案 0 :(得分:6)

在C ++ x0中,第二种方式也应该起作用。

  

初始化列表是否是在C ++中初始化类字段的唯一方法?

对于您的编译器:是的。

答案 1 :(得分:3)

静态成员可以以不同方式初始化:

class Test {
    ....
    static int x;
};

int Test::x = 5;

我不知道你是否称这个'很好',但是你可以像这样干净地初始化struct成员:

struct stype {
const char *str;
int val;
};

stype initialSVal = {
"hi",
7
};

class Test {
public:
    Test(): s(initialSVal) {}
    stype s;
};

答案 2 :(得分:1)

请注意,在某些情况下,您别无选择,只能使用初始化程序列表来设置成员的构造价值:

class A
{
 private:

  int b;
  const int c;

 public:

 A() :
  b(1),
  c(1)
 {
  // Here you could also do:
  b = 1; // This would be a reassignation, not an initialization.
        // But not:
  c = 1; // You can't : c is a const member.
 }
};

答案 3 :(得分:0)

推荐和首选的方法是初始化构造函数中的所有字段,与第一个示例完全相同。这对结构也有效。见这里:Initializing static struct tm in a class

相关问题