在上面的代码中,下面是一个类(struct)非静态数据成员hour:
vector<double> hour {vector<double>(24,not_a_reading)};
它有一个default member initializer:{vector<double>(24,not_a_reading)}
但是作者的初始化技术有什么原因
胜过仅仅做:
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 对象的一个可能原因是,在某些情况下它可能与函数声明混淆。所谓的most vexing parse。