C# 中的运算符重载
class Point
{
private int m_PointX;
private int m_PointY;
public Point(int x, int y)
{
m_PointX = x;
m_PointY = y;
}
public static Point operator+(Point point1, Point point2)
{
Point P = new Point();
P.X = point1.X + point2.X;
P.Y = point1.Y + point2.Y;
return P;
}
}
示例:
Point P1 = new Point(10,20);
Point P2 = new Point(30,40)
P1+P2; // operator overloading
- 是否有必要始终将运算符重载函数声明为静态?这背后的原因是什么?
- 如果我想重载 + 来接受像 2+P2 这样的表达式,该怎么做?
class Point
{
private int m_PointX;
private int m_PointY;
public Point(int x, int y)
{
m_PointX = x;
m_PointY = y;
}
public static Point operator+(Point point1, Point point2)
{
Point P = new Point();
P.X = point1.X + point2.X;
P.Y = point1.Y + point2.Y;
return P;
}
}
Example:
Point P1 = new Point(10,20);
Point P2 = new Point(30,40)
P1+P2; // operator overloading
- Is it necessary to always declare the operator overloading function as static? What is the reason behind this?
- If I want to overload + to accept the expression like 2+P2, how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是#2 的示例,
如果您希望
P2 + 2
工作,则必须以其他方式处理参数。请参阅 http://msdn.microsoft.com/en-us/library/8edha89s。 aspx 了解更多信息。
Here is an example for #2
You will have to do the other way with the parameters if you want
P2 + 2
to work.See http://msdn.microsoft.com/en-us/library/8edha89s.aspx for more information.
回答您的问题:
int
To answer your questions:
null
s as well.int
前面的两个答案都讨论了你的问题,所以我不会打扰这些问题,但这里有一个使用 2+P 的示例:
Both of the previous answers talk about your questions, so I'm not going to intrude on those, but here is an example of using 2+P: