vs2015-》新建控制台程序->插入如下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Operation
{
class Program
{
static void Main(string[] args)
{
//执行构造函数
Feige fei = new Feige(2, 5);
//执行构造函数
Feige ge = new Feige(3, 6);
var newfei = fei + ge;
Console.WriteLine("两对象加法操作结果是:(" + newfei.a+" ,"+ newfei.b + ")\n");
int d = (int)(fei + ge);//调用运算符+函数
//两对象加法操作结果是:55
Console.WriteLine("两对象加法操作结果是:" + d + "\n");
Console.ReadKey();
}
class Feige
{
//定义两个全局变量
public int a, b;
//声明带两个参数的构造函数
public Feige(int a, int b)
{
this.a = a;
this.b = b;
}
//重载加法运算符+
public static Feige operator +(Feige f, Feige g)
{
return new Feige(f.a + g.a, f.b + g.b);
}
//重载乘法运算符*
public static Feige operator *(Feige f, Feige g)
{
return new Feige(f.a * g.a, f.b * g.b);
}
//自定义转换类型
public static implicit operator int(Feige f)
{
return (int)(f.a * f.b);
}
}
}
}
结果: