在Stroustrup的书“编程:使用C ++编程的原理和实践(第二版)”中,作者创建了一个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}
我知道vector<double> hour(24, not_a_reading)
不会这样做,因为它初始化了两个元素24和-7777的向量,这不是所需的对象。
但是有没有理由说明作者的初始化技术优于仅仅这样做:
$attributes = array(
'type' => 'textfield',
'heading' => "HTML ID",
'param_name' => 'element_id',
'value' => '',
'description' => __( "Assign an ID to the row", "discprofile" )
);
(?)
答案 0 :(得分:4)
在上面的代码中,以下是类(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)
是的,您无法以这种方式编写类成员的初始化程序。你需要在类(struct)定义中使用花括号来使它成为初始化器,或者你可以使用语法: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 。