大佬教程收集整理的这篇文章主要介绍了c – “追溯联盟” – 可以吗?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
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 floats struct 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 – “追溯联盟” – 可以吗?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。