class Complex{
int a;
int b;
Complex(int a,int b){
this.a = a;
this.b = b;
}
Complex(){
this.a=0;
this.b=0;
}
Complex add(Complex c){
Complex r = new Complex();
r.a = this.a + c.a;
r.b = this.b + c.b;
return r;
}
Complex sub(Complex d){
Complex t=new Complex();
t.a=this.a-d.a;
t.b=this.b-d.b;
return d;
}
}
public class TestComplex {
public static void main(String[] args) {
// TODO Auto-generated method stub
Complex c1 = new Complex(40,30);
Complex c2 = new Complex(30,20);
System.out.println(c1.add(c2));
}
}
如有帮助,请点击我回答右上角【采纳】按钮
代码修改如下:
class Complex{
int a;
int b;
Complex(int a,int b){
this.a = a;
this.b = b;
}
Complex(){
this.a=0;
this.b=0;
}
Complex add(Complex c){
Complex r = new Complex();
r.a = this.a + c.a;
r.b = this.b + c.b;
return r;
}
Complex sub(Complex d){
Complex t=new Complex();
t.a=this.a-d.a;
t.b=this.b-d.b;
return d;
}
@Override
public String toString(){
return "a="+a+",b="+b;
}
}
public class TestComplex {
public static void main(String[] args) {
Complex c1 = new Complex(40,30);
Complex c2 = new Complex(30,20);
System.out.println(c1.add(c2));
}
}
因为你的add函数返回的是一个Complex对象,所以会打印对象地址
如果你想打印Complex的值,可以通过重写Complex类的toString方法来修改打印方式
有帮助望采纳~
如在类中加入
public String toString(){
return "a="+a+"\tb="+b;
}
打印对象,其实就是调用对象的toString方法,toString方法默认情况下返回对象的内存地址,如果要返回其他内容,必须重写toString方法。