8

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

除了方法中的赋值之外,初始化程序列表是在 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 MyStruct { int Number, const char* Text };

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

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

4 回答 4

6

在 C++x0 中,第二种方式也应该有效。

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

就您的编译器而言:是的。

于 2010-07-16T12:05:49.470 回答
3

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

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

int Test::x = 5;

我不知道您是否称其为“不错”,但是您可以像这样相当干净地初始化结构成员:

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

stype initialSVal = {
"hi",
7
};

class Test {
public:
    Test(): s(initialSVal) {}
    stype s;
};
于 2010-07-16T12:05:16.133 回答
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.
 }
};
于 2010-07-16T12:17:03.483 回答
0

推荐和首选的方法是初始化构造函数中的所有字段,就像在您的第一个示例中一样。这对结构也有效。请参见此处:在类中初始化静态结构 tm

于 2010-07-16T12:04:38.023 回答