用户定义的结构/类计算
User defined calculation on structs/classes
我曾经使用过Unity,他们使用一个很酷的系统来添加和相乘向量。这是参考资料的简短摘录(http://docs.unity3d.com/ScriptReference/Transform.html)
foreach (Transform child in transform) {
child.position += Vector3.up * 10.0F;
}
正如您所看到的,它们可以将两个Vector(structs/classes)相加和相乘,即使它们可能有不同的变量。现在,当我尝试进行这样的计算时,我必须将二维浮点向量的x和y分别相加。那么我如何添加像这样的结构呢
struct Vec2f{
float x;
float y;
};
一起写
Vec2f c = a + b;
而不是
c.x = a.x + b.x;
c.y = a.y + b.y;
编辑:
您需要在结构中重载运算符,如"+"、"-"等。添加示例:
struct Vec2f
{
float x;
float y;
Vec2f operator+(const Vec2f& other) const
{
Vec2f result;
result.x = x + other.x;
result.y = y + other.y;
return result;
}
};
编辑2:RIJIK在评论中问道:
我还想知道是否有一些技巧可以使函数不那么重复。我的意思是,如果我现在想使用一个运算符,我必须为每个运算符生成一个函数,即使除了所使用的运算符之外,函数之间没有太大的区别。如何实现计算或多个运算符?
所以你们可以做的一件事就是在操作符中使用另一个操作符。类似于你可以将减法改为加法,只需对第二个数字取反:
a-b变成a+(-b)
当然,您首先需要在结构中使用否定运算符来实现这一点。示例代码:
struct Vec2f
{
float x;
float y;
Vec2f operator+(const Vec2f& other) const
{
Vec2f result;
result.x = x + other.x;
result.y = y + other.y;
return result;
}
Vec2f operator-() const
{
Vec2f result;
result.x = -x;
result.y = -y;
return result;
}
// we use two operators from above to define this
Vec2f operator-(const Vec2f& other) const
{
return (*this + (-other));
}
};
其中一个好处是,例如,如果您更改加法,则不需要更改减法。它是自动更改的。
作为对此的回复:
但我不明白为什么要使函数保持不变。
因为这样你就可以把这个函数和常量变量一起使用了。例如:
const Vec2f screenSize = { 800.0f, 600.0f };
const Vec2f boxSize = { 100.0f, 200.0f };
const Vec2f sub = screenSize - boxSize;
我在这里也使用大括号初始化,因为您没有定义任何构造函数。
相关文章:
- 如何计算结构的哈希
- 使用结构数组计算文本文件中单词的出现次数C++
- 从右到左计算当前索引中的数据结构中的元素数,并打印每个元素的计数
- 如何计算结构阵列内的平均值
- 计算地图结构的哈希
- 在包含预计算结果或可计算结果的结构中使用联合
- 使用指针和结构C 计算两个点之间的距离,分割故障问题
- 如何在编译时计算c++11中的结构填充
- 通过更改代码格式来计算结构向量中包含的双精度变量的平均值的不同结果?
- 如何计算C中的结构大小
- 如何计算递归结构
- 准确计算编译器在结构中添加的填充
- 一种按排序顺序保持元素的数据结构,支持快速插入和计算连续元素之间的最大差异
- 使用复合数据结构的最近点计算
- 一个C++结构,它可以提高可读性,计算结果为零,但不是宏
- 用于选择计算机组的数据结构
- 在高性能计算中更好的做法是:将数据结构传递到一个函数或一组变量中
- 如何编写递归函数来计算图形数据结构中的最短路径
- 高效频率计算的数据结构决策.
- 如何计算结构的偏移量