我知道在Java和C#中没有类似运算符重载的东西。我的老师给我一个任务,就是用这些语言实现操作符重载。我不知道这些语言的深层概念,只有基本的OOP。所以任何一个人都可以说有没有其他方法来实现这个目标?
答案 0 :(得分:6)
在C#中有一个名为运算符重载的东西,请查看MSDN中的代码段:
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);
}
}
答案 1 :(得分:0)
如前所述,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;
}
}
这绝不是真正的运算符重载,因为你没有超载运算符。但它确实提供了以相同方式比较对象的能力。