c++ - 如何初始化类字段?

标签 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 MyStruct { int Number, const char* Text };

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

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

最佳答案

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

Are initializer lists the only way to initialize class fields in C++?

对于您的编译器而言:是的。

关于c++ - 如何初始化类字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3264597/

相关文章:

c++ - PortAudio 实时串流和处理

带有 vcl 的 C++ : closing secondary form does not end process

c++ - nghttp2-asio:在 header 中设置内容类型的正确方法

c - 如何使用最少数量的赋值运算符构建 OneTwoThree 链表?

c++ - 避免在 ctor 初始化列表中的字符串赋值中重复调用函数

C++0x : Capture By Value for Lambda, 总是一个拷贝?

c++ - 我怎样才能初始化一个对象

c++ - 类初始化中的指针初始化

c++ - 获取未初始化对象成员的地址是否定义明确?

c++ - const 字段的复杂初始化