D中的一元否定运算符重载

Sta*_*tas 5 d operator-overloading

struct test
{
   private real value;

   this(real value)
   {
      this.value = value;
   }

   bool opUnary(string op)() if (op == "!")
   {
      return !value;
   }
}

void main()
{
   test a = 123.12345;
   bool b = !a;
}
Run Code Online (Sandbox Code Playgroud)

编译错误

prog.d(19): Error: expression a of type test does not have a boolean value
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/Kec81

也在dmd 2.053,2.054上测试

我的代码出了什么问题?

小智 3

您不能重载!D 中的运算符 - 请参阅http://www.d-programming-language.org/operatoroverloading.html#Unary以获取可重载一元运算符的列表。在不知道自己在做什么的情况下,很难建议解决方法,但可能值得一看alias this- http://www.d-programming-language.org/class.html#AliasThis

  • 谢谢。看来你是对的。这是《D 编程语言》中的一个示例。看来我需要重载cast(bool)。 (2认同)
  • 请注意,缺少所有逻辑运算符。IIRC 这是故意的。 (2认同)