请问JAVA里面有对运算符的重载吗,我这个对“+”的重载可以吗?
编译通不过,,,请问怎么对“+”做重载??
package myclass;
class Complex{
private double real;
private double imag;
public Complex(){
this.real=0;
thix.imag=0;
}
public Complex(int real){
this.real=real;
this.imag=0;
}
public Complex(int real,int imag){
this.real=real;
this.imag=imag;
}
public Complex(Complex c){
this.real=c.real;
this.imag=c.imag;
}
public Complex operator +(Complex c){
Complex a=new Comlex(this.real+c.real,this.imag+c.imag);
return a;
}
public Complex operator +(double d){
Complex b=new Complex(this.real+d,this.imag);
return b;
}
public static Complex operator +(Complex c1,Complex c2){
Complex c=new Complex(c1.real+c2.real,c1.imag+c2.imag);
return c;
}
public static Complex operator +(Complex c,double d){
Complex c=new Complex(c.real+d,c.imag);
return c;
}
public String toString(){
String s;
if(this.imag==0)
s=String.valueOf(this.real);
if(this.imag<0)
s=real+"("+imag+")i";
else
s=real+"+"+imag+"i";
}
}
public class SY3{
public static void main(String[] args){
Complex c1=new Complex(5,-5);
Complex c2=new Complex(4,7);
Complex c3=c1+c2;
System.out.println(c3.toString());
}
}
------解决方案--------------------
抱歉,Java不支持对运算符进行重载。
------解决方案--------------------
或者应该说,不支持你写程序去对运算符实现重载。
语言本身提供的重载能力,比如+用于“字符串连接”这种,提供了就提供了,没提供的你也没招去增加它。