重载+/-一元运算符 [英] Overloading +/- unary operators
本文介绍了重载+/-一元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当重载-一元运算符时,对于不可变类型,可以这样写:
When you overload the - unary operators, for an immutable type, you can write it like:
public static Point3 operator - (Point3 p)
{
return new Point3 (-p.X, -p.Y, -p.Z);
}
但是对于+一元运算符,您应该如何实现呢?像这样:
But for the + unary operator, how should you implement it? Like this:
public static Point3 operator + (Point3 p)
{
return p;
}
或类似这样:
public static Point3 operator + (Point3 p)
{
return new Point3 (p);
}
推荐答案
两种方法都可以.您不会使用这两种方法中的任何一种来对原始对象进行变异.
Either way is fine. You are not mutating the original object in either of the two methods.
如果调用string.substring(0, string.length())
,则没有理由无法返回原始字符串.
If you call string.substring(0, string.length())
, there is no reason why the original string cannot be returned.
您唯一签署的具有不变性的合同是,一旦创建了对象,它就不会改变.
The only contract you sign with immutability is that once an object is created, it doesn't change.
这篇关于重载+/-一元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文