如何使用构造函数以类似的方式初始化"对象数组"
how to initialize 'array of object' with constructor in a similar way for 'an object'
如果有一个对象,我们可以通过以下方式使用构造函数初始化它 -
class obj{
int x;
public:
obj(int n) {x=n;}
};
int main()
{
obj p(2);
}
对象数组有完全相同的方法吗;我的意思是完全相同的方式。
我知道使用构造函数初始化对象的另外两种方法 -
obj p = obj(2);
obj p = 2; // for one parameter constructor
并且有等效的方法来初始化对象数组 -
obj p = {obj(1), obj(2), obj(3), obj(4)};
obj p[] = {1, 2, 3, 4};
但我未能找到类似的方法来初始化单个对象的第一个代码中显示的对象数组。
如果我理解你的问题没错...
// Initialize array member varible - method 1
struct Foo
{
int a[3] = {1, 2, 3};
};
// Initialize array member varible - method 2
struct Bar
{
Bar() : a{1, 2, 3} {}
int a[3];
};
// Can't do this.
struct Foo
{
int a[] = {1, 2, 3};
};
这将做到这一点:
#include <array>
class obj{
int x;
public:
obj(int n) {x=n;}
};
int main()
{
std::array<obj,3> p = {3, 7, 11};
}
std::array 提供与基元数组类型相同的语义,但符合 C++ 容器的条件。您可能最好使用 std::vector,它提供动态调整大小和更多保护:
#include <vector>
...
std::vector<obj> p = {obj(1), obj(2), obj(4)};
使用通用容器的好处是,您通常可以互换使用它们:
#include <vector>
//#include <array>
#include <algorithm>
...
int main()
{
std::vector<obj> p = {obj(1), obj(2), obj(4)};
// or the following:
// std::array<obj,3> p = {obj(1), obj(2), obj(4)};
// either one of the above will work here
std::for_each(begin(p), end(p),
[](obj const & o){ std::cout << o.x << " "; });
std::cout << std::endl;
// ^^^ yes, this only works if x is public
}
请注意,std::array 的大小在编译时是有大小的,因此它确实需要你告诉它元素的数量。
还可以重写原始类以使用初始值设定项列表构造,如下所示:
class obj{
int x;
public:
obj(int n) : x(n) { }
};
即使在此示例中,它也可能会有所帮助,因为它允许您 x
const
.一般来说,它有很多好处,是一个养成的好习惯。
相关文章:
- Constexpr替代了新的放置方式,可以让内存中的对象保持未初始化状态
- 为什么C++有不同的变量初始化方式?
- 为什么两种不同的对象初始化方式给出不同的输出
- 以这种方式初始化的 char 数组是否会自动添加空终止符?
- C++中数据初始化的不同方式
- 用初始化列表和超类构造函数声明子类构造函数的正确方式
- 在 C 语言中初始化 List<List> 的优雅方式<Coordinate>#
- 是否可以以编程方式初始化 constexpr std::array 成员
- 初始化结构的两种方式
- 如何以包装的方式初始化布局,从而减少布局之间的空间
- 高效而优雅的矢量初始化方式
- 卡在理解以下初始化方式shared_ptr
- 在现代C++中初始化字符串的方式是否有不同
- 如何以静态方式使用另一个 constexpr 数组初始化一个数组
- 这些在C 中初始化C数组的方式之间有区别吗?
- 干燥的方式来构建具有相同初始化器列表的数组的所有元素
- 优雅的方式,将初始化器移动到有条件的循环后面
- C++数组初始化的特殊方式
- 容器初始化方式
- C++结构初始化方式