Dmi*_*sev 17 java operator-overloading
我有以下类,它描述XY表面上的一个点:
class Point{
double x;
double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我想overlad +和-运营商有可能写代码运行:
Point p1 = new Point(1, 2);
Point p2 = new Point(3, 4);
Point resAdd = p1 + p2; // answer (4, 6)
Point resSub = p1 - p2; // answer (-2, -2)
Run Code Online (Sandbox Code Playgroud)
我怎么能用Java做呢?或者我应该使用这样的方法:
public Point Add(Point p1, Point p2){
return new Point(p1.x + p2.x, p1.y + p2.y);
}
Run Code Online (Sandbox Code Playgroud)
提前致谢!
mač*_*ček 11
你不能用Java做到这一点.您必须在班级中实施plus或add方法Point.
class Point{
public double x;
public double y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
public Point add(Point other){
this.x += other.x;
this.y += other.y;
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
用法
Point a = new Point(1,1);
Point b = new Point(2,2);
a.add(b); //=> (3,3)
// because method returns point, you can chain `add` calls
// e.g., a.add(b).add(c)
Run Code Online (Sandbox Code Playgroud)
尽管你不能在纯java中做到这一点,你可以使用java-oo编译器插件来做到这一点.你需要为+运算符编写add方法:
public Point add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
Run Code Online (Sandbox Code Playgroud)
和java-oo插件只是desugar运算符到这些方法调用.
在 Java 中无法执行此操作,因为 Java 中没有运算符重载。
您必须使用您提到的第二个选项:
编辑:您可以Add在 Point 类本身中添加该方法
public Point Add(Point other){
return new Point(this.x + other.x, this.y + other.y);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31731 次 |
| 最近记录: |