在 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."
我知道
vector<double> hour{24, not_a_reading}
不会这样做,因为它初始化了一个包含两个元素的向量,24 和 -7777,这不是所需的对象。但是有什么理由说明作者的初始化技巧比仅仅做的要好:
vector<double> hour(24, not_a_reading)
(?)
最佳答案
在上面的代码中,下面是一个类(结构体)非静态数据成员hour
:
vector<double> hour {vector<double>(24,not_a_reading)};
它有一个 default member initializer :
{vector<double>(24,not_a_reading)}
But is there any reason why the author's initialization technique is superior to just doing:
vector<double> hour(24, not_a_reading)
是的,您将无法以这种方式编写类成员的初始化程序。您需要类(结构)定义中的花括号使其成为初始值设定项,或者您可以使用以下语法:
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;
}
一个可能的原因是
vector<double> hour(24,not_a_reading);
不允许创建 hour
object 是因为在某些情况下它可能与函数声明混淆。所谓的most vexing parse .
关于c++11 - 关于在 C++11 中初始化向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37767641/