dimanche 16 juillet 2017

Initialize constants which are instance of complex class/struct (C++)

I often want to define several constants which are instances of common class or struct. I didn't figured out any way how to do it when class contains pointers to other structs or dynamic arrays.

Example:

I want to write header file Solids.h which defines general class Solid and than define several constant instances like Tetrahedron, Cube, Octahedron, Icosahedron.

Following solution does not work: compiler complains that it is unable initialize pointers in 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*2] = { {0,1},{0,2},{0,3},{1,2},{1,3},{2,3}};
    static Vec3i     Tetrahedron_tris    [Tetrahedron_ntris *3] = { {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

Aucun commentaire:

Enregistrer un commentaire