运算符重载

1、C++中的运算符重载

  用 operator 关键字申明运算符的重载。

  新建类 mCurPoint ,该类继承自 mCPoint。

  .h文件中申明类,及成员函数:

  class mCurPoint :public mCPoint

  {
  public:
    mCurPoint(void);
    mCurPoint(double x ,double y);
    ~mCurPoint(void);
  public:
    double getArea();
    double distancTo(mCurPoint oPt);
    mCurPoint operator- (const mCurPoint& p2) const;
   mCurPoint operator+ (const mCurPoint& p2) const;
  };

  如上,红色部分分别重载加号运算(+)和减号运算(-)。由于加号(+)和减号(-)是二元运算符,除本身(this 指针)之外还需要另外一个变量,因此还需要给函数增加一个参数 p2。

  运算结果需要有返回值(没有返回值也可以,不过就没有意义了),因此需要有返回值类型。这里是 mCurPoint  类型,也可以是其他类型,根据具体情况而定。

  

  在 .cpp 文件中定义实现函数(运算符重载部分):

  mCurPoint mCurPoint::operator- (const mCurPoint& p2) const
  {
    double x = p2.mpX - this->mpX;
    double y = p2.mpY - this->mpY;
    mCurPoint mPot (x,y);
    return mPot;
  }
  mCurPoint mCurPoint::operator+ (const mCurPoint& p2) const
  {
    double xx = (this->mpX + p2.mpX)/2;
    double yy = (this->mpY + p2.mpY)/2;
    mCurPoint mPot(xx,yy);
    return mPot;
  }

  在函数中,根据需要,但会符合实际的结果即可。

  重载运算符的使用

  mCurPoint pot(1,3);                              //定义pot
  mCurPoint pot2 (3,3);                             //定义第二个变量
  mCurPoint resPot = pot2 - pot;                        //计算结果
  cout<<"pot2 - pot :x="<<resPot.mpX<<"; y = " <<resPot.mpY<<endl;   //输出结果
  mCurPoint sumPot = pot2 + pot;
  cout<<"pot2 + po2 : x= "<<sumPot.mpX<<"; y = "<<sumPot.mpY<<endl;

  

2、c#中的运算符重载

  和C++类似,定义一个类,使用 operator 关键字重载运算符。

  class ClsAppple
  {
    public double height;
    public double Radiuo;
    public string name;
    public static ClsAppple operator-(ClsAppple cl1,ClsAppple cl2)
    {
      ClsAppple newAp = new ClsAppple() { name = "NULL", height = cl1.height - cl2.height, Radiuo = cl1.Radiuo - cl2.Radiuo };
      return newAp;
    }
  }

  和C++不同的是,运算符减号(-)是二元操作符,所以需要在函数中传递两个参数。

  重载后,即可直接使用:

  ClsAppple cl1 = new ClsAppple()
  {
    Radiuo = 10,
    height = 0.5,
    name = "N1"
  };
  ClsAppple cl2 = new ClsAppple()
  {
    name = "N2",
    height = 2,
    Radiuo = 20
  };
  ClsAppple resApp = cl1 - cl2;
  string rsStr = String.Format("Res: R = {0}; H = {1}; N = {2}", resApp.Radiuo, resApp.height, resApp.name);

自定义类一般不直接支持标准运算(如:+,-,*,/,+=,-=......等),使用运算符不仅可以使自定义类支持标准运算,还可以根据需要返回合适类型和值。不仅可以减少程序代码量,也大大增强了程序的可读性,同时也是面向对象中多态的体现。

原文地址:https://www.cnblogs.com/xtblog/p/5647117.html