用户定义的结构/类计算

User defined calculation on structs/classes

本文关键字:计算 结构 定义 用户      更新时间:2023-10-16

我曾经使用过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;

我在这里也使用大括号初始化,因为您没有定义任何构造函数。