template <int N> class Vector{ float data[N]; //etc. (math,mostly)};class Vector3 : public Vector<3>{ //Vector3-specific stuff,like the cross product};
现在,我想在子类中使用x / y / z成员变量(完整成员,而不仅仅是getter – 我希望能够设置它们).但是为了确保所有(继承的)数学运算出来,x必须引用与data [0],y到data [1]等相同的内存.基本上,我想要一个联合,但我不能在基类中声明一个,因为我不知道该点向量中的浮点数.
那么 – 这可以吗?是否有某种预处理器/ typedef /模板魔法可以实现我正在寻找的东西?
PS:我正在使用g 4.6.0和-std = c 0x,如果这有帮助的话.
编辑:虽然引用会给出我正在寻找的语法,但理想的解决方案不会使类更大(并且引用做了很多!Vector< 3>是12字节.带引用的Vector3是40!) .
解决方法 怎么样:class Vector3 : public Vector<3>{public: // initialize the references... Vector3() : x(data[0]),y(data[1]),z(data[2]){}private: float& x; float& y; float& z;};
当然,如果你想让它们占据同一个空间,那就是另一个故事……
使用一点模板魔法,您可以执行以下 *** 作…
#include <iostream>template <int N,typename UnionType = voID*> struct Vector{ union { float data[N]; UnionType fIEld; }; voID set(int i,float f) { data[i] = f; } // in here,Now work with data voID print() { for(int i = 0; i < N; ++i) std::cout << i << ":" << data[i] << std::endl; }};// define a structure of three floatsstruct float3{ float x; float y; float z;};struct Vector3 : public Vector<3,float3>{};int main(voID){ Vector<2> v1; v1.set(0,0.1); v1.set(1,0.2); v1.print(); Vector3 v2; v2.fIEld.x = 0.2; v2.fIEld.y = 0.3; v2.fIEld.z = 0.4; v2.print();}
编辑:读完评论后,我意识到我之前发布的内容确实没有什么不同,所以稍微调整一下上一次迭代就可以直接访问该字段(这就是我猜你会想到的) – 我猜这个区别而Rob的解决方案是你不需要所有专业知识来反复实现所有逻辑……
总结以上是内存溢出为你收集整理的c – “追溯联盟” – 可以吗?全部内容,希望文章能够帮你解决c – “追溯联盟” – 可以吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)