美文网首页
C++运算符重载

C++运算符重载

作者: 贝克街的猫大哥呀 | 来源:发表于2017-08-29 17:22 被阅读0次

先看一个简单的

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++多态。运算符重载将重载的概念扩展到运算符上,允许赋予C++运算符多种含义。...

  • 1.2.15_C++ 关系运算符重载

    C++ 重载运算符和重载函数 C++ 语言支持各种关系运算符( < 、 > 、 <= 、 >= 、 == 等等),...

  • C++ 运算符重载

    运算符重载将重载的概念扩展到运算符上,允许赋予C++运算符多种含义。实际上,很多C++运算符已经重载。将*运算符用...

  • C++运算符重载

    C++运算符重载的实质:运算符重载的实质就是函数重载或函数多态。运算符重载是一种形式的C++多态。目的在于让人能够...

  • C++运算符重载-下篇 (Boolan)

    C++运算符重载-下篇 (Boolan) 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符...

  • C++运算符重载-上篇 (Boolan)

    C++运算符重载-上篇 (Boolan) 本章内容:1. 运算符重载的概述2. 重载算术运算符3. 重载按位运算符...

  • C++ 重载运算符

    C++重载运算符

  • C++重载

    重载 C++语言规定: 重载的运算符要保持原运算符的意义。只能对已有的运算符重载,不能增加新的运算符。重载的运算符...

  • 1.2.17_C++ ++ 和 -- 运算符重载

    C++ 重载运算符和重载函数 递增运算符( ++ )和递减运算符( -- )是 C++ 语言中两个重要的一元运算符...

  • C++运算符重载详解

    运算符重载规则 1.被重载的运算符必须是已经存在的C++运算符,不能重载自己创建的运算符; 2.运算符被重载之后,...

网友评论

      本文标题:C++运算符重载

      本文链接:https://www.haomeiwen.com/subject/xlxadxtx.html