C#运算符重载

2017-09-18  本文已影响6人  晓龙酱
class Salary{

    public Salary(int val){
        this.val = val;
    }

    public int val
    {
        private set;
        get;
    }

    override public string ToString()
    {
        return val.ToString();
    }
<font color=blue>
    static public Salary operator +(Salary a, Salary b){
        return new Salary(a.val + b.val);
    }

    static public Salary operator -(Salary a, Salary b){
        return new Salary(a.val - b.val);
    }
</font>
}
Salary s1 = new Salary(1);
Salary s2 = new Salary(2);
Salary r1 = s1 + s2;        // 3
Salary r2 = s1 - s2;        // -1
上一篇下一篇

猜你喜欢

热点阅读