D运算符重载

Erd*_*dem 3 d operator-overloading

import std.stdio;

struct Vector2
{
    float x, y;

    this (float x, float y)
    {
        this.x = x;
        this.y = y;
    }

    // vector2 * number
    Vector2 opBinary(string op)(const float rhs)
    if (op == "*")
    {
        auto result = this;
        this *= rhs;
        return this;
    }

    // number * vector2
    Vector2 opBinaryRight(string op)(const float lhs)
    if (op == "*")
    {
        return this.opBinary!(op)(lhs);
    }

    /*
      assignment operators
    */

    // vector2 = vector2
    ref Vector2 opAssign(const ref Vector2 rhs)
    {
        x = rhs.x;
        y = rhs.y;
        return this;
    }

    // vector2 *= number
    ref Vector2 opOpAssign(string op)(const float rhs)
    if (op == "*") {
        x *= rhs;
        y *= rhs;
        return this;
    }
}

unittest
{
    auto first = Vector2(1, 2);
    auto second = Vector2(3, 3);
    auto number = 4.0f;

    Vector2 result = first *= 3;
    assert(result == Vector2(3, 6));
    // BUG *
    // assert(first == Vector2(1, 2));    
}

void main() 
{}
Run Code Online (Sandbox Code Playgroud)

你好.当我尝试使用-unittest选项编译这个小程序时,为什么最后一个断言失败了?任何帮助,将不胜感激.谢谢..

Pet*_*der 5

你为什么期望它通过?

first *= 3修改first,因此它不保留其原始值.

也许你打算写

Vector2 result = first * 3;
Run Code Online (Sandbox Code Playgroud)

还有一个问题 Vector2 opBinary(string op)(const float rhs)

该函数就像表达式中使用的那样10 * v.您的代码this在表达式中修改this *= rhs.该功能应该实施:

auto result = this;
result *= rhs;
return result;
Run Code Online (Sandbox Code Playgroud)