能給出個運算符重載的例子嗎﹐﹐謝謝

LiSDN 2003-10-20 09:56:47
能給出個運算符重載的例子嗎﹐﹐謝謝
...全文
36 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xdf_hubei 2003-10-20
  • 打赏
  • 举报
回复
// complex.cs
using System;

public struct Complex
{
public int real;
public int imaginary;

public Complex(int real, int imaginary)
{
this.real = real;
this.imaginary = imaginary;
}

// Declare which operator to overload (+), the types
// that can be added (two Complex objects), and the
// return type (Complex):
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
}
// Override the ToString method to display an complex number in the suitable format:
public override string ToString()
{
return(String.Format("{0} + {1}i", real, imaginary));
}

public static void Main()
{
Complex num1 = new Complex(2,3);
Complex num2 = new Complex(3,4);

// Add two Complex objects (num1 and num2) through the
// overloaded plus operator:
Complex sum = num1 + num2;

// Print the numbers and the sum using the overriden ToString method:
Console.WriteLine("First complex number: {0}",num1);
Console.WriteLine("Second complex number: {0}",num2);
Console.WriteLine("The sum of the two numbers: {0}",sum);

}
}
输出
First complex number: 2 + 3i
Second complex number: 3 + 4i
The sum of the two numbers: 5 + 7i
tacittui 2003-10-20
  • 打赏
  • 举报
回复
public static Address operator -(Address a1,Address a2)
{
Address a3 = new Address();
//......
return a3;
}

public static Address operator +(Address a1,Address a2)
{
Address a3 = new Address();
//......
return a3;
}
public static Address operator ++(Address a1)
{
Address a3 = new Address();
//......
return a3;
}

110,526

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧