C++运算符重载

先看一个简单的

class Point{

   public:

   int x;

   int y;

   public:

    Point(int x = 0, int y = 0){

       this->x = x;

       this->y = y;

}

void myprint(){

   cout << x << "," << y << endl;

  }

};

//重载+号

Point operator+(Point &p1, Point &p2){

Point tmp(p1.x + p2.x, p1.y + p2.y);

return tmp;

}

//重载-号

Point operator-(Point &p1, Point &p2){

   Point tmp(p1.x - p2.x, p1.y - p2.y);

   return tmp;

}

void main(){

    Point p1(10,20);

    Point p2(20,10);

    Point p3 = p1 + p2;

    p3.myprint();

    system("pause");

}

如上,按这个套路重新写运算符就行了,这个例子是在类的外部定义的,一般来说,是在类内部定义,如下:、

class Point{

   public:

   int x;

   int y;

   public:

   Point(int x = 0, int y = 0){

   this->x = x;

   this->y = y;

}

   //成员函数,运算符重载

   Point operator+(Point &p2){

       Point tmp(this->x + p2.x, this->y + p2.y);

        return tmp;

  }

void myprint(){

    cout << x << "," << y << endl;

  }

};

void main(){

   Point p1(10, 20);

   Point p2(20, 10);

   //运算符的重载,本质还是函数调用

   //p1.operator+(p2)

   Point p3 = p1 + p2;

   p3.myprint();

   system("pause");

}

这样写就是在类的内部定义

但是,但类的成员变量是private时,这样写就不行了,就必须要用友元函数来解决这个重定义的问题:

class Point{

      friend Point operator+(Point &p1, Point &p2);

       private:

       int x;

       int y;

   public:

      Point(int x = 0, int y = 0){

        this->x = x;

        this->y = y;

}

   void myprint(){

      cout << x << "," << y << endl;

   }

};

Point operator+(Point &p1, Point &p2){

     Point tmp(p1.x + p2.x, p1.y + p2.y);

return tmp;

}

void main(){

   Point p1(10, 20);

   Point p2(20, 10);

   //运算符的重载,本质还是函数调用

   //p1.operator+(p2)

   Point p3 = p1 + p2;

   p3.myprint();

   system("pause");

}

这样就解决了~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • C++运算符重载-下篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 1,492评论 0 49
  • C++运算符重载-上篇 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符和二元逻辑运算符4...
    Haley_2013阅读 2,336评论 0 51
  • //出自51博客:www.Amanda0928.51.com 第一章 一、选择题 1.B; (typedef ,t...
    Damongggggg阅读 11,260评论 0 1
  • 运算符重载规则 1.被重载的运算符必须是已经存在的C++运算符,不能重载自己创建的运算符; 2.运算符被重载之后,...
    随波逐流007阅读 745评论 0 1
  • 说明 继续上面的内容要求: 按照数组下标由小到大,数组下标运算符按照次序分别返回圆心x坐标,圆心y坐标,圆的半径。...
    qratosone阅读 372评论 0 0