如何初始化 2-dim 数组,它是 C++ 中的结构成员
How to initialize 2-dim array which is a struct member in C++
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;
}
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?