命名空间中常量结构、类和数组的初始化

Initialization of constant structures, classes and arrays in namespace

本文关键字:数组 初始化 常量 结构 命名空间      更新时间:2023-10-16

我想制作命名空间Solids它只存储有关几个常见实体(如柏拉图实体)的顶点和边/面连接的信息。

所以我Solids.h做了这个头文件:

#ifndef  Solids_h
#define  Solids_h
#include "Vec3.h" // this is my class of 3D vector, e.g. class Vec3d{double x,y,z;}
namespace Solids{
    struct Tetrahedron{
        const static int    nVerts = 4;
        const static int    nEdges = 6;
        const static int    nTris  = 4;
        constexpr static Vec3d verts [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} };
        constexpr static int   edges [nEdges][2] = { {0,1},{0,2},{0,3}, {1,2},{1,3},{2,3} };
        constexpr static int   tris  [nTris ][3] = { {0,1,2},{0,1,3},{0,2,3},{1,2,3} };
    } tetrahedron;
};
#endif

然后在我的程序中,其中包括Solids.h我想像这样绘制它:

void drawTriangles( int nlinks, const int * links, const Vec3d * points ){
    int n2 = nlinks*3;
    glBegin( GL_TRIANGLES );
    for( int i=0; i<n2; i+=3 ){
        Vec3f a,b,c,normal;
        convert( points[links[i  ]], a ); // this just converts double to float verion of Vec3
        convert( points[links[i+1]], b );
        convert( points[links[i+2]], c );
        normal.set_cross( a-b, b-c );
        normal.normalize( );
        glNormal3f( normal.x, normal.y, normal.z );
        glVertex3f( a.x, a.y, a.z );
        glVertex3f( b.x, b.y, b.z );
        glVertex3f( c.x, c.y, c.z );
    }
    glEnd();
};
// ommited some code there
int main(){
   drawTriangles( Solids::tetrahedron.nTris, (int*)(&Solids::tetrahedron.tris[0][0]), Solids::tetrahedron.verts );
}

但是当我这样做时,我会undefined reference to Solids::Tetrahedron::verts.这可能与这个未定义的引用到静态常量问题有关。

所以我想解决方案应该是在namespace{}之外和声明之外初始化它struc{}

喜欢:

Solids::Tetrahedron::tris [Solids::Tetrahedron::nTris ][3] = { {0,1,2},{0,1,3},{0,2,3},{1,2,3} };

或:

Solids::Tetrahedron.tris [Solids::Tetrahedron.nTris ][3] = { {0,1,2},{0,1,3},{0,2,3},{1,2,3} };

没有更优雅的解决方案吗?

您可以使用 constexpr 静态成员函数,而不是使用 constexpr 数据成员。

struct Tetrahedron{
    constexpr static int    nVerts = 4;
    constexpr static int    nEdges = 6;
    constexpr static int    nTris  = 4;
    constexpr static Vec3d[nverts] verts() { return { {-1.0d,-1.0d,-1.0d}, {+1.0d,+1.0d,-1.0d}, {-1.0d,+1.0d,+1.0d}, {+1.0d,-1.0d,+1.0d} }; }
    constexpr static int[nEdges][2] edges() { return { {0,1},{0,2},{0,3}, {1,2},{1,3},{2,3} }; }
    constexpr static int[nTris ][3] tris() { return { {0,1,2},{0,1,3},{0,2,3},{1,2,3} }; }
} tetrahedron;