在类内部初始化字段的原因是什么? [英] What's the reason for initializing fields inside class?

查看:83
本文介绍了在类内部初始化字段的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,可以在类中直接初始化类的字段的值,例如:

In C++ it is possible to initialize values of class's fields durectly in class, like:

class X
{
  int a = 5;
}

原因是什么?在哪里有用?默认的ctor完全一样。似乎我无法使用位掩码( int a:3 )初始化值。

What's the reason for it? Where it can be useful? The default ctor does exactly the same. And it seems like I cannot initialize values with bit masks (int a : 3).

推荐答案

来自权威(这看起来很相似到早期的标准提案 N2756 ):

From the authority (this reads pretty similar to the earlier standard-proposal N2756):


类内成员初始化程序



在C ++ 98中,只能在类中初始化整型的静态const成员,并且初始化程序必须是一个常量表达式。这些限制确保我们可以在编译时进行初始化。例如:

In-class member initializers

In C++98, only static const members of integral types can be initialized in-class, and the initializer has to be a constant expression. These restrictions ensure that we can do the initialization at compile-time. For example:

int var = 7;

int var = 7;

class X {
    static const int m1 = 7;        // ok
    const int m2 = 7;                   // error: not static
    static int m3 = 7;              // error: not const
    static const int m4 = var;          // error: initializer not constant expression
    static const string m5 = "odd"; // error: not integral type
    // ...
};

C ++ 11的基本思想是允许将非静态数据成员初始化为它被声明(在其类中)。然后,在需要运行时初始化时,构造函数可以使用初始化程序。考虑:

The basic idea for C++11 is to allow a non-static data member to be initialized where it is declared (in its class). A constructor can then use the initializer when run-time initialization is needed. Consider:

class A {
public:
    int a = 7;
};

这等效于:

class A {
public:
    int a;
    A() : a(7) {}
};

这样可以节省一些键入时间,但是真正的好处是具有多个构造函数的类。通常,所有构造函数都为成员使用通用的初始化程序:

This saves a bit of typing, but the real benefits come in classes with multiple constructors. Often, all constructors use a common initializer for a member:

class A {
public:
    A(): a(7), b(5), hash_algorithm("MD5"), s("Constructor run") {}
    A(int a_val) : a(a_val), b(5), hash_algorithm("MD5"), s("Constructor run") {}
    A(D d) : a(7), b(g(d)), hash_algorithm("MD5"), s("Constructor run") {}
    int a, b;
private:
    HashingFunction hash_algorithm;  // Cryptographic hash to be applied to all A instances
    std::string s;                   // String indicating state in object lifecycle
};

hash_algorithm和s都有一个默认值的事实在代码混乱中丢失了,很容易在维护期间成为问题。相反,我们可以排除数据成员的初始化:

The fact that hash_algorithm and s each has a single default is lost in the mess of code and could easily become a problem during maintenance. Instead, we can factor out the initialization of the data members:

class A {
public:
    A(): a(7), b(5) {}
    A(int a_val) : a(a_val), b(5) {}
    A(D d) : a(7), b(g(d)) {}
    int a, b;
private:
    HashingFunction hash_algorithm{"MD5"};  // Cryptographic hash to be applied to all A instances
    std::string s{"Constructor run"};       // String indicating state in object lifecycle
};

如果成员同时由类内初始化程序和构造函数初始化,则仅构造函数的初始化为完成(覆盖默认设置)。因此,我们可以进一步简化:

If a member is initialized by both an in-class initializer and a constructor, only the constructor's initialization is done (it "overrides" the default). So we can simplify further:

class A {
public:
    A() {}
    A(int a_val) : a(a_val) {}
    A(D d) : b(g(d)) {}
    int a = 7;
    int b = 5;  
private:
    HashingFunction hash_algorithm{"MD5"};  // Cryptographic hash to be applied to all A instances
    std::string s{"Constructor run"};       // String indicating state in object lifecycle
};


这篇关于在类内部初始化字段的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆