我经常想要定义几个常量class
或struct
的常量。当类包含指向其他结构或动态数组的指针时,我没有想出如何做到这一点。
示例:
我想编写头文件Solids.h
,它定义了一般class Solid
,并定义了几个常量实例,如Tetrahedron, Cube, Octahedron, Icosahedron
。
以下解决方案不起作用:编译器抱怨它无法初始化Solid Tetrahedron
中的指针
Solids.h|45|error: cannot convert ‘Vec3d (*)[4] {aka Vec3TYPE<double> (*)[4]}’ to ‘Vec3d* {aka Vec3TYPE<double>*}’ in initialization|
#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
答案 0 :(得分:0)
指向数组的指针(如&Tetrahedron_verts
)与指向元素的指针(如Vec3d * verts
)不同。您可能希望指针verts
指向数组的第一个元素,这样您就可以执行Tetrahedron.verts[k]
之类的操作。
所以你可以做&Tetrahedron_verts[0]
,这是有效的。
但是你不需要,因为大多数时候数组的名称会自动衰减到指向第一个元素的指针:
const static Solid Tetrahedron = {
Tetrahedron_nverts, Tetrahedron_nedges, Tetrahedron_ntris,
Tetrahedron_verts, Tetrahedron_edges, Tetrahedron_tris
};
请注意,您在汇总初始值设定项之前也不需要(Solid)
类型名称。