求C#大神,编程关于类及其对象的封装

u010356531 2013-04-28 05:51:42
编写一个Complex类(复数),该类中有以下字段
real:复数的实部
imag:复数的虚部
请使用属性对上述字段进行封装,并有以下方法
Add:复数的加法,包括复数与复数的加法,复数与实数的加法。
Subtract:复数的减法,包括复数与复数的减法,复数与实数的减法。
ToString:将复数以a+bi的形式输出。
...全文
78 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
u010356531 2013-05-02
  • 打赏
  • 举报
回复
这就是传说中的大C#神吗!真得很感谢
图灵狗 2013-04-28
  • 打赏
  • 举报
回复
参考以下代码,根据其中+运算符重载,可以简单的编写Add和Subtract函数:

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

    public Complex(int real, int imaginary)  //constructor
    {
        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 a complex number in the traditional format:
    public override string ToString()
    {
        return (System.String.Format("{0} + {1}radius", real, imaginary));
    }
}

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

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

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

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    First complex number:  2 + 3i
    Second complex number: 3 + 4i
    The sum of the two numbers: 5 + 7i
*/

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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