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);
}
求指导哪里有错?
代码:
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);
}
}