【问题标题】:How to achieve operator overloading in java and C#?java和C#中如何实现运算符重载?
【发布时间】:2012-11-24 15:07:13
【问题描述】:

我知道在 Java 和 C# 中没有运算符重载之类的东西。我的老师给了我一个任务,以在任何这些语言中实现运算符重载。我不知道这些语言的深层概念,只知道基本的 OOP。那么有人能说有没有其他方法可以实现这一目标?

【问题讨论】:

标签: c# java polymorphism operator-overloading


【解决方案1】:

C#中有一个叫运算符重载的东西,看看MSDN的这段代码sn-p:

public struct Complex 
{
   public int real;
   public int imaginary;

   public Complex(int real, int imaginary) 
   {
      this.real = real;
      this.imaginary = imaginary;
   }

   // Declare which operator to overload (+), the types 
   // that can be added (two Complex objects), and the 
   // return type (Complex):
   public static Complex operator +(Complex c1, Complex c2) 
   {
      return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
   }
}

Full list of overloadable operators

【讨论】:

  • 太棒了..我不知道。我注意到 C#。如果你也可以在 java 中给我一些类似的解决方案,我会标记你的答案。谢谢
  • 我不是Java专家,但据我所知,其中没有运算符重载。
  • 好吧,我会等待其他答案,如果我对其他人不满意,我会肯定地标记你的..
  • 还要确保您确实需要运算符重载,也许您只需要创建一些类似AddRemove 的方法
  • 不,我的老师问我的问题是直截了当的,即在这两个语言中实现运算符重载。没有提供其他信息。
【解决方案2】:

正如 des 所示,C# 确实有运算符重载。另一方面,Java 没有。 Java 比较两个对象是否相等的方式是通过重写方法equals(Object) 来完成的,该方法继承自基础对象java.lang.Object。这是一个示例用法:

public class MyClass {
    private int value;

    @Override
    public boolean equals(Object o) {
        return o instanceof MyClass && ((MyClass)o).value == this.value;
    }
}

当然,这只是复制重载== 运算符的一种解决方法。对于其他运算符,例如>=<=,则没有任何内容。但是,您可以使用 OO 来某种通过使用通用接口重新创建它:

interface Overloadable<T> {
    public boolean isGreaterThan(T other);
    public boolean isLessThan(T other);
}

public class MyClass implements Overloadable<MyClass> {
    private int value;

    @Override
    public boolean equals(Object o) {
        return o instanceof MyClass && ((MyClass)o).value == this.value;
    }

    @Override
    public boolean isGreaterThan(MyClass other) {
        return this.value > other.value;
    }

    @Override
    public boolean isLessThan(MyClass other) {
        return this.value < other.value;
    }
}

这绝不是真正的运算符重载,因为您并没有重载运算符。但是,它确实提供了以相同方式比较对象的能力。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2016-02-19
    • 2013-11-22
    • 1970-01-01
    相关资源
    最近更新 更多