Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/137.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何初始化';对象数组';以类似的方式为';对象';_C++_Arrays - Fatal编程技术网

C++ 如何初始化';对象数组';以类似的方式为';对象';

C++ 如何初始化';对象数组';以类似的方式为';对象';,c++,arrays,C++,Arrays,如果有一个对象,我们可以用构造函数按以下方式初始化它- 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),

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

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};
}

即使在本例中,它也可能有所帮助,因为它允许您生成
x
const
。一般来说,它有很多好处,是一个好习惯

对于obj p[]={1,2,3,4},它似乎可以正常工作:/@NathanOliver不理解第二种方法。第二种方法类似于初始化非数组类型的成员。如果你有一个成员
intb
,您可以在构造函数的成员初始值设定项部分用
b{20}
初始化它。我不知道结构有构造函数部分:/and冒号是什么?@syednakibossain、
struct
class
的行为非常相似。主要区别在于
struct
s的默认访问权限是
public
,而
class
的默认访问权限是
private
@syednakibossain冒号中的成员初始值设定项列表:和
#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
}
class obj{
  int x;
 public:
  obj(int n) : x(n) { }
};