才知道java竟然没有运算符重载

Java doesn’t support user-defined operator overloading. The preferred approach is to define a method on your class to perform the action: a.add(b) instead of a + b.
The only aspect of Java which comes close to “custom” operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer.

刚从c++转到java,才知道java不支持运算符重载,比如要实现对象间的加法,需要定义add函数,用a.add(b)而不能用a+b。
当然,字符串的合并(”+”操作)可以算是一种运算符重载,但是也仅限于这种情况。
其实,我主要是想吐槽写复数类的乘法和除法真的是要写死人了。。。

public class Complex {

    private Fraction realPart;
    private Fraction imagePart;

    public Complex(Fraction real,Fraction image){
        realPart=new Fraction(real);
        imagePart=new Fraction(image);
    }

...

    public Complex multiply(Complex complex) {
        Fraction real=realPart.multiply(complex.realPart).subtract(imagePart.multiply(complex.imagePart));
        Fraction image=realPart.multiply(complex.imagePart).add(imagePart.multiply(complex.realPart));
        return new Complex(real,image);
    }

    public Complex divide(Complex complex) {
        Fraction real=realPart.multiply(complex.realPart).add(imagePart.multiply(complex.realPart)).divide(complex.realPart.multiply(complex.realPart).add(complex.imagePart.multiply(complex.imagePart)));

        Fraction image=imagePart.multiply(complex.realPart).subtract(realPart.multiply(complex.imagePart)).divide(complex.realPart.multiply(complex.realPart).add(complex.imagePart.multiply(complex.imagePart)));

        return new Complex(real,image);
    }

【参考资料】
https://stackoverflow.com/questions/77718/why-doesnt-java-offer-operator-overloading
https://stackoverflow.com/questions/1686699/operator-overloading-in-java

你可能感兴趣的:(java学习笔记,java)