操作符的重载

开头,我是兴冲冲地要试如下的代码:
using System;

public class m
{
 
static void Main()
 
{
  Console.WriteLine(
12+15);
 }

 
public static int operator +(int x, int y)
 
{
  
return x+y*2;
 }

}
我想让全部的+号改成自己乱七八糟的算法,但编译器却告诉我:
p.cs(9,20): error CS0563: 二元运算符的参数之一必须是包含类型
而如果使用以下代码,编译不会出错,但结果没有效果:
using System;

public class m
{
 
static void Main()
 
{
  Console.WriteLine(
12+15);
 }


 
public static int operator +(int x, m y)
 
{
  
return x+y*2;
 }

 
public static implicit operator int(m x)
 
{
  
return x;
 }

 
public static implicit operator m(int x)
 
{
  
return x;
 }

}
我又将操作符用到稍微实际的地方去,代码如下:
using System;

public class m
{
 
static void Main()
 
{
  point p
=new point();
  p
=p+3;
  p.show();
 }

}


class point
{
 
private int x=0;
 
public static point operator +(point p, int i)
 
{
  p.x
=p.x+i*2;
  
return p;
 }

 
public void show()
 
{
  Console.WriteLine(
"x=" + x);
 }

}

这样才可以看得出效果了。

测试时发现,如果要想使用p=3+p;这样的语句,必须再定义一个
 public static point operator +(int i, point p)
否则就会提示:
p.cs(9,5): error CS0019: 运算符“+”无法应用于“int”和“point”类型的操作数
这样说来,操作符重载对我来说还是挺多疑问,还好,至少目前我还没需要用到。

原文地址:https://www.cnblogs.com/yzx99/p/1218757.html