【问题标题】:Can you initialise in the class and in the constructor and is that correct? [duplicate]您可以在类和构造函数中进行初始化吗?对吗? [复制]
【发布时间】:2020-06-08 09:45:45
【问题描述】:

考虑下面的代码:

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

我的问题是,你能在类和构造函数体中同时拥有初始化值吗? - 编译器如何解决这个问题?看来构造函数获胜,因为该程序的输出是:

t1:1.123
t2:2.456

【问题讨论】:

  • 您显示的代码很好,并且“我假设现在这会覆盖“默认”初始化值?”是正确的。
  • 谢谢 - 我将帖子链接到建议的问题,该问题也有我正在寻找的答案:)

标签: c++ constructor initialization


【解决方案1】:

是的,对于default member initializer

通过一个默认成员初始化器,它是一个大括号或等于成员声明中包含的initializer,并且在构造函数的成员初始化器列表中省略该成员时使用。

如果一个成员有一个默认的成员初始化器并且还出现在构造器的成员初始化列表中,那么该构造器的默认成员初始化器将被忽略。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    相关资源
    最近更新 更多