2011-06-04 117 views
3
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() 
{} 

嗨。当我试图用-unittest选项编译这个小程序时,为什么最后一个断言失败?任何帮助,将不胜感激。谢谢..D运营商超载

回答

5

你为什么期望它通过?

first *= 3修改first,所以它不保留其原始值。

也许你的意思是写

Vector2 result = first * 3; 

还拥有Vector2 opBinary(string op)(const float rhs)

这个函数就是在表达式中使用像10 * v问题。您的代码在表达式this *= rhs中修改了this。该功能应执行:

auto result = this; 
result *= rhs; 
return result; 
+0

当然:)谢谢。 – Erdem 2011-06-04 14:51:26