运算符重载常见问题:C#二元运算符的参数之一必须是包含类型

先来看看下面的这段代码

01usingSystem;
02usingSystem.Collections.Generic;
03usingSystem.Linq;
04usingSystem.Text;
05usingSystem.Drawing;
06namespaceConsoleApplication1
07{
08    classShape
09    {
10        publicint Width { get;set; }
11        publicint Height { get;set; }
12        publicShape(int width, int height)
13        {
14            this.Width = width;
15            this.Height = height;
16        }
17        publicShape()
18        {
19            
20        }
21        publicstatic Shape operator+(Shape shap1, Shape shape2)
22        {
23            Shape temp =new Shape();
24            temp.Width = shap1.Width + shape2.Width;
25            temp.Height = shape2.Height + shap1.Height;
26            returntemp;
27        }
28    }
29
30        classProgram
31        {
32            staticvoid Main(string[] args)
33            {
34                Shape shape1 =new Shape(1, 1);
35                Shape shape2 =new Shape(2, 2);
36                Shape shape = shape1 + shape2;
37                Console.WriteLine(shape.Width);
38                Console.WriteLine(shape.Height);
39                Console.ReadKey();
40            }
41        }
42}

[info]
输出:
3
3
[/info]
还是上面这段代码,如果我们改变一个运算符重载那块代码的位置,变成如下:

01usingSystem;
02usingSystem.Collections.Generic;
03usingSystem.Linq;
04usingSystem.Text;
05usingSystem.Drawing;
06namespaceConsoleApplication1
07{
08    classShape
09    {
10        publicint Width { get;set; }
11        publicint Height { get;set; }
12        publicShape(int width, int height)
13        {
14            this.Width = width;
15            this.Height = height;
16        }
17        publicShape()
18        {
19
20        }
21
22    }
23
24    classProgram
25    {
26        publicstatic Shape operator+(Shape shap1, Shape shape2)
27        {
28            Shape temp =new Shape();
29            temp.Width = shap1.Width + shape2.Width;
30            temp.Height = shape2.Height + shap1.Height;
31            returntemp;
32        }
33        staticvoid Main(string[] args)
34        {
35            Shape shape1 =new Shape(1, 1);
36            Shape shape2 =new Shape(2, 2);
37            Shape shape = shape1 + shape2;
38            Console.WriteLine(shape.Width);
39            Console.WriteLine(shape.Height);
40            Console.ReadKey();
41        }
42    }
43}

[info]这个时候,我们重新运行这段代码,便会报“二元运算符的参数之一必须是包含类型”的错误[/info]

导致报二元运算符的参数之一必须是包含类型错误的原因有哪些

(1)就是跟我们的上面代码类似的情况,两个参数都是Shape类型,但是由于重载代码的位置放的不正确,就导致这个错误

(2)就是运算符重载的地方,所有的参数都不是重载返回的类型。比如我们Shape类型,那么你的参数里面至少有一个必须是Shape类型的参数


转自:http://www.iamlisen.com/c-is-one-of-the-parameters-of-a-binary-operator-must-be-the-containing-type.html

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值