我试图在类中重载除法运算符以返回double。
我有两个课程:Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_EMAIL, addresses);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
和Length
。在Angle
类中,我有接受不同三角比率的初始化器。这是一个例子:
Angle
public class Angle
{
public double Degrees;
public double Minutes;
public double Etc;
public Angle(double radians)
{
// Main initialization here.
}
public static Angle FromTangent(double tangent)
{
return new Angle(Math.Atan(tangent));
}
}
类将测量输入转换为不同的度量单位。最后一种方法真的会让生活更轻松:
Length
问题是最后两种方法不明确。我做了一些研究,隐式转换似乎是正确的学习路径。我尝试了以下方法,似乎没有正确的语法:
public class Length
{
public double Inches;
public double Feet;
public double Meters;
public double Etc;
public enum Unit { Inch, Foot, Meter, Etc };
public Length(double value, Unit unit)
{
// Main initialization here.
}
public static Length operator /(Length dividend, Length divisor)
{
double meterQuotient = dividend.Meters / divisor.Meters;
return new Length(meterQuotient, Unit.Meter);
}
// This is what I want to be able to do.
public static double operator /(Length dividend, Length divisor)
{
double ratio = dividend.Meters / divisor.Meters;
return ratio;
}
}
最终
我希望能够分割两个 public static implicit operator double /(Length dividend, Length divisor) { }
public static double implicit operator /(Length dividend, Length divisor) { }
public static implicit double operator /(Length dividend, Length divisor) { }
个对象,并获得一个双倍。它仅对除法有效,因为它返回的是比率,而不是单位数。如果这是可能的,那么实现将非常简单,而且非常棒。这就是为什么我想知道这是否可行的原因。
Length
这可以在仍然能够让我的其他分区操作员过载的情况下完成吗?
答案 0 :(得分:4)
转换不是一个部门 - 这是两个独立的操作。你似乎正试图将它们合并在一起。
从根本上说,您似乎应该删除此运算符:
// Kill this
public static Length operator /(Length dividend, Length divisor)
它根本没有意义 - 如你所提到的,长度除以长度是比率,它不是长度。 5米/ 2米是2.5,而不是2.5米。
删除后,没有歧义,所以你很好。
另一方面,有英寸,英尺,米等字段对我来说似乎是一个坏主意。您可能希望有两个字段,其中一个是幅度,另一个是单位(可能是枚举)。