如何使用构造函数以类似的方式初始化"对象数组"

how to initialize 'array of object' with constructor in a similar way for 'an object'

本文关键字:初始化 方式 对象 数组 何使用 构造函数      更新时间:2023-10-16

如果有一个对象,我们可以通过以下方式使用构造函数初始化它 -

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 .一般来说,它有很多好处,是一个养成的好习惯。