运算符重载

 
 

using System;

using System.Collections.Generic;

using System.Text;

 
 

namespace WindowsFormsApplication3

{

public
class
Class1

{

public
int a;

public
int b;

 
 

public Class1(int a,int b)

{

this.a = a;

this.b = b;

}

 
 

public
string tostring()

{

return a.ToString() + “+” + b.ToString() + “i”;

}

 
 

public
static
Class1
operator +(Class1 a1, Class1 a2)

{

Class1 c = new
Class1(0,0);

c.a = a1.a + a2.a;

c.b = a1.b + a2.b;

return c;

}

}

}

 
 

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

 
 

namespace WindowsFormsApplication3

{

public
partial
class
Form1 : Form

{

public Form1()

{

InitializeComponent();

}

 
 

private
void button1_Click(object sender, EventArgs e)

{

Class1 c1 = new
Class1(1,2);

Class1 c2 = new
Class1(3,4);

Class1 c3 = c1 + c2;

MessageBox.Show(c3.tostring());

}

}

}

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注