Class 初始化作为复杂类/结构(C+;+;)实例的常量

Class 初始化作为复杂类/结构(C+;+;)实例的常量,class,c++11,struct,initialization,Class,C++11,Struct,Initialization,我经常想定义几个常量,它们是公共类或结构的实例。当类包含指向其他结构或动态数组的指针时,我并没有想出任何方法来实现这一点 示例: 我想编写头文件Solids.h,它定义了一般的类Solid,然后定义了几个常量实例,如四面体、立方体、八面体、二十面体 以下解决方案不起作用:编译器抱怨无法初始化实心四面体中的指针 Solids.h | 45 |错误:无法在初始化中将'Vec3d(*)[4]{aka Vec3TYPE(*)[4]}转换为'Vec3d*{aka Vec3TYPE*}'。 #ifndef

我经常想定义几个常量,它们是公共
结构
的实例。当类包含指向其他结构或动态数组的指针时,我并没有想出任何方法来实现这一点

示例:

我想编写头文件
Solids.h
,它定义了一般的
类Solid
,然后定义了几个常量实例,如
四面体、立方体、八面体、二十面体

以下解决方案不起作用:编译器抱怨无法初始化实心四面体中的指针

Solids.h | 45 |错误:无法在初始化中将'Vec3d(*)[4]{aka Vec3TYPE(*)[4]}转换为'Vec3d*{aka Vec3TYPE*}'。

#ifndef  Solids_h
#define  Solids_h

#include "Vec2.h"
#include "Vec3.h"

class Solid{ public:
    int nvert;
    int nedge;
    int ntri;
    Vec3d * verts;
    Vec2i * edges;
    Vec3i * tris;
};

namespace Solids{

    // ==== Tetrahedron
    const static int Tetrahedron_nverts = 4;
    const static int Tetrahedron_nedges = 6;
    const static int Tetrahedron_ntris  = 4;
    static Vec3d     Tetrahedron_verts   [Tetrahedron_nverts]   = { {-1.0d,-1.0d,-1.0d}, {+1.0d,+1.0d,-1.0d}, {-1.0d,+1.0d,+1.0d}, {+1.0d,-1.0d,+1.0d} };
    static Vec2i     Tetrahedron_edges   [Tetrahedron_nedges] = { {0,1},{0,2},{0,3},{1,2},{1,3},{2,3}};
    static Vec3i     Tetrahedron_tris    [Tetrahedron_ntris] = { {0,2,1},{0,1,3},{0,3,2},{1,2,3} };

    const static Solid Tetrahedron = (Solid){Tetrahedron_nverts,Tetrahedron_nedges,Tetrahedron_ntris, &Tetrahedron_verts,&Tetrahedron_edges,&Tetrahedron_tris};
};

#endif
指向数组的指针(如
&四面体顶点
)不同于指向元素的指针(如
Vec3d*顶点
)。您可能希望指针
verts
指向数组的第一个元素,这将允许您执行
四面体.verts[k]
之类的操作

所以你可以做
&四面体顶点[0]
,这是有效的

但您不需要这样做,因为大多数时候数组的名称会自动衰减为指向第一个元素的指针:

const static Solid Tetrahedron = {
    Tetrahedron_nverts, Tetrahedron_nedges, Tetrahedron_ntris,
    Tetrahedron_verts, Tetrahedron_edges, Tetrahedron_tris
};

注意,在聚合初始值设定项之前也不需要
(实心)
类型名称。

为什么要将计数乘以2和3?数组大小指定元素的数量,如
Vec2i
Vec3i
,而不是用于创建它们的整数总数。因此,这实际上是在数组的末尾放置了不需要的默认构造向量。aschepler-啊哈,对不起,我的实现略有不同(它是
int*
而不是
Vec*
),我在为这个问题格式化代码时忘记了这个
*2
*3
。我现在改正了