【问题标题】:About initializing a vector in C++11关于在 C++11 中初始化向量
【发布时间】:2016-10-12 13:36:17
【问题描述】:

在 Stroustrup 的《Programming: Principles and Practices of Programming Using C++ (Second Edition)》一书中,作者创建了一个struct,如下:

const int not_a_reading = –7777;

struct Day {
vector<double> hour {vector<double>(24,not_a_reading)};
};
// As the author says: "That is, a Day has 24 hours, 
// each initialized to not_a_reading."

我知道vector&lt;double&gt; hour{24, not_a_reading} 不会这样做,因为它初始化了一个包含两个元素的向量,24 和 -7777,这不是所需的对象。

但是有什么理由让作者的初始化技术优于仅仅做:

vector<double> hour(24, not_a_reading)

(?)

【问题讨论】:

    标签: c++11 vector constructor


    【解决方案1】:

    在上面的代码中,下面是一个类(struct)非静态数据成员hour

    vector<double> hour {vector<double>(24,not_a_reading)};
    

    它有一个default member initializer{vector&lt;double&gt;(24,not_a_reading)}

    但是作者的初始化技术有什么原因 胜过仅仅做:

    vector<double> hour(24, not_a_reading)
    

    是的,你不能这样写类成员的初始化器。您需要在类(结构)定义中使用花括号来使其成为初始化程序,或者您可以使用语法:vector&lt;double&gt; hour = vector&lt;double&gt;(24,not_a_reading);,这意味着同样的事情。

    #include <vector>
    
    using namespace std;
    
    int main()
    {
        const int not_a_reading = -7777;
    
        struct Day {
            vector<double> hour{vector<double>(24,not_a_reading)}; // create a vector of doubles object with the constructor and then initialize hour with 24 doubles
            vector<double> hour2 = vector<double>(24,not_a_reading); // same as above
        };
    
        //struct Day2 {
        //  vector<double> hour(24,not_a_reading); // syntax error
        //};
    
        struct Day3 {
          vector<double> hour(int,int); // function declaration!
        };
    
        vector<double> other_hour(24,not_a_reading); // ok here
        vector<double> other_hour2(); // function declaration, most vexing parse!
        vector<double> another_hour{vector<double>(24,not_a_reading)}; // also ok here
    
        return 0;
    }
    

    vector&lt;double&gt; hour(24,not_a_reading); 不允许创建hour 对象的一个​​可能原因是,在某些情况下它可能与函数声明混淆。所谓的most vexing parse

    【讨论】:

    • 更准确地说,“你不能这样写类成员的初始化器”。该语法对于局部和全局变量的初始化仍然完全有效。 (不,它不是一个函数声明——尽管与一个混淆的可能性是类成员初始化器需要大括号或等号的原因)
    猜你喜欢
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2015-09-20
    • 1970-01-01
    • 2020-10-10
    • 2012-06-21
    • 2013-05-10
    相关资源
    最近更新 更多