点点滴滴


         从点开始绘制自己的程序人生
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

正确的重载operator

Posted on 2006-12-16 15:38  点点滴滴  阅读(543)  评论(0编辑  收藏  举报
           用户定义类型选择正确的重载operator+的一般性处理例如我们在赋值语句中经常使用 a+=1 ; b-=2; c*=3; d/=3;  如果x和y是用户定义的类型, 就不能确保这样。
        代码如下 :
 1   public class Saver : IDisposable
 2    {
 3        // Fields
 4        private TextBox m_textBox;
 5
 6        private int m_start, m_end;
 7
 8        /// <summary>
 9        ///   Initializes a new instance of the Saver class by associating it with a TextBoxBase derived object. </summary>
10        /// <param name="textBox">
11        ///   The TextBoxBase object for which the selection is being saved. </param>
12        /// <remarks>
13        ///   This constructor saves the textbox's start and end position of the selection inside private fields. </remarks>
14        /// <seealso cref="System.Windows.Forms.TextBoxBase" />    

15        public Saver(TextBox textBox)
16        {
17            m_textBox = textBox;
18        }

19
20        public static Saver operator +(Saver saver, int pos)
21        {
22            return new Saver(saver.m_textBox, saver.m_start + pos, saver.m_end + pos);
23        }

24
25        public void MoveBy(int start, int end)
26        {
27            m_start += start;
28            m_end += end;
29
30            Debug.Assert(m_start <= m_end);
31        }

32    }

33