代码之家  ›  专栏  ›  技术社区  ›  Roman Starkov

如何初始化类字段?

  •  7
  • Roman Starkov  · 技术社区  · 15 年前

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

    是初始值设定项列表 只有 除了方法的赋值外,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 回复  |  直到 15 年前
        1
  •  6
  •   BeachBlocker    15 年前

    在C++ X0中,第二种方法也应该工作。

    初始化器列出了C++中初始化类字段的唯一方法吗?

    对于编译器:是的。

        2
  •  3
  •   sje397    15 年前

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

    class Test {
        ....
        static int x;
    };
    
    int Test::x = 5;
    

    我不知道您是否称之为“nice”,但您可以非常清楚地初始化结构成员,如下所示:

    struct stype {
    const char *str;
    int val;
    };
    
    stype initialSVal = {
    "hi",
    7
    };
    
    class Test {
    public:
        Test(): s(initialSVal) {}
        stype s;
    };
    
        3
  •  1
  •   ereOn    15 年前

    只需提到,在某些情况下,除了使用初始值设定项列表在构造上设置成员的值之外,您别无选择:

    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.
     }
    };
    
        4
  •  0
  •   Community Mohan Dere    8 年前

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

    推荐文章