向量具有一个不错的显式构造函数,它允许以给定数量的给定值来初始化向量,例如对于INT的向量:
std::vector<int> v(16, 0); // 16 zero ints.
我想使用此语法(或类似的简单语法)来初始化成员变量。我该如何实现?我忽略了什么吗?
我做了一些实验:
#include <iostream>
#include <vector>
struct Foo
{
Foo()
// : v(16, 0) // B: Uncomment for case B.
{
std::cout << "v:" << v.size() << "n";
}
// This is what I want: Vector with 16 zero ints, all details near the member definition.
// A: Intuitive, but does not compile: error: expected identifier before numeric constant.
// std::vector<int> v(16,0);
// B: Old style. Works, but requires details in each constructor and far from the definition.
// std::vector<int> v;
// C: Two ints. List initialization.
// std::vector<int> v{16,0};
// D: One int. List initialization with comma operator expression.
// std::vector<int> v{(16,0)};
// E: Works for 16 but not for (1<<20). Ugly.
// std::vector<int> v{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// F: Works. The best I came up with so far. Somewhat redundant.
std::vector<int> v = std::vector<int>(16, 0);
// Question: Is there something shorter than F, more like A?
} foo;
int main()
{
// This is what I would like to be able to do for class member initialization:
std::vector<int> v2(16,0); // 16 ints.
std::cout << "v2:" << v2.size() << "n";
}
具体问题:是否比F?
更短/更简单奖励问题:直接支持列表初始化语法的基本原理是什么,而不是正常的构造函数语法(例如 A a(4, 8)
?。
(对于我的实验,我在Linux和C 17上使用了GCC 8.1。)
虽然有一些冗余,但使用
在概念上没有错std::vector<int> v = std::vector<int>(16, 0);
使用
Foo() : v(16, 0) {}
同样好。
如果有多个构造函数,您绝对不想重复每个构造函数中的v(16, 0)
部分。在这种情况下,使用委派构造函数是一种选择。如果您班上有更多的构造函数,我无法提出任何具体的建议。
您可以在http://www.stroustrup.com/c 11faq.html#delegating-ctor.
直接支持成员变量的列表初始化语法的理由是什么,而不是正常的构造函数语法(例如a a(4,8)?我认为支持案例A没有问题,我发现它是直观的。
虽然您的示例很好,请想象您有
struct A {};
struct foo
{
A a();
};
什么是a
?是函数还是默认的初始化A
。即使添加了一套空括号的规则被认为是一个函数,我们也会遇到相同的问题
struct A {};
struct B {};
struct foo
{
A a(B());
};
作为 a
可以是采用函数类型的函数,或者是默认构造对象的变量。
是否比f?
更短/更简单
在C 17中,随着类模板参数的引入,您可以将初始化变成
std::vector<int> foo{std::vector(16, 0)}; // the 0 is used to deduce int for the vector in the braces
较短,但我不确定它是否更清晰或更容易理解。