命名空间中常量结构、类和数组的初始化
Initialization of constant structures, classes and arrays in namespace
我想制作命名空间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;
相关文章:
- C++使用整数的压缩数组初始化对象
- C++17中函数模板中的静态数组初始化(MSVC 2019)
- 从另一个静态常量数组初始化静态常量数组(只需少量计算)
- 在 Python 和 c++ 2d 数组初始化之间.这是怎麽?为什么呢?
- 字节数组初始化会导致 DirectX 崩溃
- 使用 new 和 值进行数组初始化,但没有显式数量的元素
- 运行时C++数组初始化问题
- 使用带有参数包的数组的成员数组初始化类
- 仅通过C++中数组初始化的不同方法,即可在同一输入上获得两个不同的答案
- C++ 2 个指针数组初始化 C2440
- C++结构字符数组初始化
- C++中的多维数组初始化
- constexpr数组初始化
- C++引物动态数组初始化程序的数目超过大小
- 使用std::index_sequence对std::数组初始化进行包扩展
- 当 std 数组初始化太小时,C++会引发错误吗?
- 如何确定结构数组初始化的大小?
- Qt并发错误:数组初始化需要大括号括起来的初始值设定项列表
- 此代码中的数组初始化样式是什么?这是标准的吗?
- C++ 使用数组初始化时的 STL 向量内存管理