如何重载操作符和转换操作符

using System;
 
class Complex
{
    public int i;
    public Complex(int i)
    {
        this.i = i;
    }
    //操作符重载,本质上是一个方法
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.i + c2.i);
    }
}
class TalentType
{
    public int i;
    public double l;
    //针对不同的类型设计的构造器
    public TalentType(int i)
    {
        this.i = i;
    }
    public TalentType(double l)
    {
        this.l = l;
    }
    //自定义的转换函数
    public int ToInt32()
    {
        return this.i;
    }
    public double Todouble()
    {
        return this.l;
    }
 
    /*以下是操作符转换,本质上也是一个方法*/
 
    //隐式的类型操作符转换
    public static implicit operator TalentType(int i)
    {
        return new TalentType(i);
    }
    public static implicit operator TalentType(double l)
    {
        return new TalentType(l);
    }
    //显式的类型操作转换
    public static explicit operator Int32(TalentType t)
    {
        return t.i;
    }
    public static explicit operator double(TalentType t)
    {
        return t.l;
    }
 
}
class App
{
    static void Main(string[] args)
    {
        //操作符重载
        Complex c1 = new Complex(3);
        Complex c2 = new Complex(4);
 
        Complex c3 = c1 + c2;
        Console.WriteLine("after c1 add c2,c3.i={0}", c3.i);
 
        //隐式操作符转换
        TalentType t1 = 10;
        TalentType t2 = 2.3;
 
        //显式操作符转换
        int i = (int)t1;
        double l = (double)t2;
 
        Console.Read();
    }
}

 

posted @ 2010-02-25 15:49  吴永富  阅读(253)  评论(0编辑  收藏  举报