你能在 class 和构造函数中初始化吗?

Can you initialise in the class and in the constructor and is that correct?

考虑以下代码:

#include <iostream>

class tester
{
public:
    tester(){}
    explicit tester(double val) : 
        m_a(val) // I assume this now overwrites the "default" initialise value?
    {}
    double m_a {1.123}; // Default constructor value?
};


int main()
{
    tester t1;
    tester t2(2.456);

    std::cout << "t1:" << t1.m_a << std::endl;
    std::cout << "t2:" << t2.m_a << std::endl;

    return 0;
}

我的问题是,您可以在 class 和构造函数主体中同时拥有初始化值吗? - 编译器如何解决这个问题?似乎构造函数获胜,因为该程序的输出是:

t1:1.123
t2:2.456

是,default member initializer

Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored for that constructor.

在默认构造函数中m_a没有在成员初始化器列表中被提及,那么它将被默认成员初始化器初始化为1.123。在 tester::tester(double)m_a 将由成员初始化列表初始化为参数 val