如何使用其定义附近的显式长度/值构造函数初始化向量成员变量
How can I initialize a vector member variable using the explicit length/value constructor near its definition?
向量具有一个不错的显式构造函数,它允许以给定数量的给定值来初始化向量,例如对于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
较短,但我不确定它是否更清晰或更容易理解。
相关文章:
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 我们可以用参数化构造函数初始化结构的数组吗?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 类内初始化与构造函数初始化列表的顺序
- 通过 C++ 中的重载构造函数初始化未知类型的变量
- 使用复制构造函数初始化 new[]
- 如何从子类的构造函数初始化父类的私有成员
- 在构造函数初始化列表中使用 std::variant
- 使用构造函数初始化结构还是在之后设置其值更好?
- C++ 没有匹配的构造函数初始化 []
- 我正在使用dev c ++,但收到错误(C++98'array'必须由构造函数初始化)
- 使用所述填充构造函数初始化向量中的向量
- 如何同时创建一个具有两个或多个构造函数初始化的对象
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 这是使用构造函数初始化数组对象的最佳方法吗?
- 内置类型的构造函数初始化
- 构造函数初始化和对象损坏