一些基本问题,但我很难跟踪一个明确的答案。

是初始化程序列出了只有的方式来初始化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 initializer初始化struct字段?例如:

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

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

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

有帮助吗?

解决方案

在c ++ x0中,第二种方式也应该工作。

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

在您的编译器中

:是的。

其他提示

静态成员可以初始化:

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;
};
.

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

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.
 }
};
.

推荐和首选的方法是初始化构造函数中的所有字段,就像在第一个示例中一样。这也适用于结构。请参阅这里:初始化静态结构tm

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top