求关于运算符重载的问题

.Net技术 码拜 8年前 (2016-09-19) 997次浏览
Rect是一个结构体,想重载+运算,代码如下,会报错:One of the parameters of a binary operator must be the containing type(二元运算符的参数之一必须是包含类型)
代码:
public static Rect operator +(Rect a,Rect b)
{
Rect c = new Rect(0,0,0,0);
c.x = a.x + b.x;
c.y = a.y + b.y;
c.width = a.width + b.width;
c.height = a.height + b.height;
return c;
// return new Rect(a.x+b.x,a.y+b.y,a.width+b.width,a.height+b.height);
}
求指导哪里有错?
解决方案

10

运算符重载只能在类的内部定义。
说白了,就是只有类的开发者有权利做运算符重载。

10

struct Rect
{
    public int X;
    public int Y;
    public int Width;
    public int Height;
    public Rect(int x, int y, int w, int h)
    {
        X = x;
        Y = y;
        Width = w;
        Height = h;
    }
    public static Rect operator +(Rect a, Rect b)
    {
        return new Rect(a.X + b.X, a.Y + b.Y, a.Width + b.Width, a.Height + b.Height);
    }
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明求关于运算符重载的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)