如何初始化 2-dim 数组,它是 C++ 中的结构成员

How to initialize 2-dim array which is a struct member in C++

本文关键字:C++ 结构 成员 它是 初始化 2-dim 数组      更新时间:2023-10-16
struct abc {
    double matrix[2][2];
};
int main(){
   abc test;
   test.matrix[2][2]={0,0,0,0};
}

我构造了一个名为 abc 的结构,2*2 矩阵是它的 memember。但是如何在主函数中初始化矩阵呢?上面的代码总是带有错误...如何解决?

另请参阅此和此

你可以写:

struct abc 
{
    int foo;
    double matrix[2][2];
};
void f()
{
   abc test = 
       { 
        0,        // int foo; 
        {0,0,0,0} // double matrix[2][2];
       };
}

我添加了foo,以明确为什么数组周围有额外的{}集。

注意这种结构初始化只能与aggregate data type一起使用,这大致是指C-link结构。

如果你真的需要构造然后分配,你可能需要做这样的事情:

struct Matrix
{
    double matrix[2][2];
};
struct abc2 
{       
    int foo;
    Matrix m;
};
void g()
{
   abc2 test;
   Matrix init =  { 5,6,7,8};
   test.m = init;
}

gcc 4.5.3: g++ -std=c++0x -wall -wextra struct-init.cpp

struct abc {
  double matrix[2][2];
};
int main(){
 abc test;
 test.matrix = {{0.0,0.0},{0.0,0.0}};
}

或者也许简单是最好的:

struct abc {
  double matrix[2][2];
  abc() {
    matrix[0][0] = 0.0; matrix[0][1] = 0.0;
    matrix[1][0] = 0.0; matrix[1][1] = 0.0; }
};
int main(){
 abc test;
}