0
struct abc {
    double matrix[2][2];
};

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

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

4

2 回答 2

0

另请参阅 和此

你可以写:

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;
}
于 2013-09-09T05:21:26.440 回答
0

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;
}
于 2013-09-09T04:00:32.543 回答