关于在 C++11 中初始化向量

Aky*_*Aky 5 constructor vector c++11

在 Stroustrup 的《Programming: Principles and Practices of Programming Using C++(第二版)》一书中,作者创建了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."
Run Code Online (Sandbox Code Playgroud)

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

但是有什么理由说明作者的初始化技巧比仅仅做的要好:

vector<double> hour(24, not_a_reading)
Run Code Online (Sandbox Code Playgroud)

(?)

wal*_*lly 5

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

vector<double> hour {vector<double>(24,not_a_reading)};
Run Code Online (Sandbox Code Playgroud)

它有一个默认的成员初始值设定项{vector<double>(24,not_a_reading)}

但是有什么理由说明作者的初始化技巧比仅仅做的要好:

vector<double> hour(24, not_a_reading)
Run Code Online (Sandbox Code Playgroud)

是的,您将无法以这种方式编写类成员的初始化程序。您需要类(结构)定义中的花括号使其成为初始值设定项,或者您可以使用语法:vector<double> hour = vector<double>(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;
}
Run Code Online (Sandbox Code Playgroud)

vector<double> hour(24,not_a_reading);不允许创建hour对象的一个可能原因是在某些情况下它可能与函数声明混淆。所谓最头疼的解析