operator Overloading in C#

こ雲淡風輕ζ 提交于 2020-06-22 11:28:25

问题


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
  1. Is it necessary to always declare the operator overloading function as static? What is the reason behind this?
  2. If I want to overload + to accept the expression like 2+P2, how to do this?

回答1:


  1. Yes. Because you aren't dealing with instances always with the operators.
  2. Just change the types to what you want.

Here is an example for #2

public static Point operator+(int value, Point point2)
{
 // logic here.
}

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.




回答2:


To answer your questions:

  1. Yes, you need to define them as static. They're not instance methods, they can operate on nulls as well.
  2. You'll have to define an operator overload where one of the parameters are of type int



回答3:


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:

   public static Point operator+(int yourInt, Point point)
    {
        Point P = new Point();
        P.X = point.X + yourInt;
        P.Y = point.Y + yourInt;

        return P;
    }


来源:https://stackoverflow.com/questions/5966392/operator-overloading-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!