C++运算符重载(类内、外重载) 您所在的位置:网站首页 成员函数重载和非成员函数重载 C++运算符重载(类内、外重载)

C++运算符重载(类内、外重载)

2024-07-11 22:38| 来源: 网络整理| 查看: 265

1.概念

  运算符的重载,实际是一种特殊的函数重载,必须定义一个函数,并告诉C++编译器,当遇到该运算符时就调用此函数来行使运算符功能。这个函数叫做运算符重载函数(常为类的成员函数)。   用函数的方式实现了(+ - * / []数组 && || 逻辑 等)运算符的重载。根据需求决定重载那些运算符,用到的时候再百度案例即可。

2.运算符重载的基本格式

   返回值类型 类名::operator重载的运算符(参数表)    {    ……    }

   operator是关键字,它与重载的运算符一起构成函数名。

3.运算符重载的两种方法 二元运算符重载

1.类内重载

#include using namespace std; class Point{ public: Point(){}; Point (int x, int y): x(x),y(y) {}; Point operator+(const Point &b){ //类内重载,运算符重载函数作为类的成员函数 Point ret; ret.x = this->x + b.x; ret.y = this->y + b.y; return ret; } int x,y; }; int main() { Point a(2,4),b(5,3); Point c = a + b; //这里c++编译器会,自动去找 + 运算符的重载函数 cout}; Point (int x, int y): x(x),y(y) {}; friend Point operator+(const Point &, const Point &); //声明类的友元函数 int x,y; }; Point operator+(const Point &a,const Point &b){//类外重载,运算符重载函数作为类的友元函数 Point ret; ret.x = a.x + b.x; ret.y = a.y + b.y; return ret; } int main() { Point a(2,4),b(5,3); Point c = a + b; cout}; friend ostream &operator cout }; friend Point operator+(const Point &, const Point &); friend ostream &operator//后置++,不需要引用返回,需要参数区分。返回自增前的值,且返回的是一个右值 Point temp(x,y); //因为后置++,是先使用,后自++,所以这里要保存一个临时值,再++,返回的是临时值。 this->x ++; this->y ++; return temp; } private: int x,y; }; Point operator+(const Point &a,const Point &b){ Point ret; ret.x = a.x + b.x; ret.y = a.y + b.y; return ret; } ostream &operator Point a(2,4),b(5,3); Point c = a + b; cout m_len = obj.m_len; m_p = (char *)malloc(m_len + 1); strcpy(m_p, obj.m_p); } //等号运算符重载函数 Name& operator=(Name &obj) { //1.先释放旧的内存 if (this->m_p != NULL) { delete[] m_p; m_len = 0; } //2.根据obj分配内存大小 this->m_len = obj.m_len; this->m_p = new char [m_len+1]; //加1,结束符'\n'。 //3.把obj赋值 strcpy(m_p, obj.m_p); //字符串的拷贝函数 return *this; } ~Name() //析构函数 { if (m_p != NULL) { free(m_p); m_p = NULL; m_len = 0; } } protected: private: char *m_p ; int m_len; }; void main() { Name obj1("abcdefg"); Name obj2 = obj1; //C++编译器提供的 默认的copy构造函数 浅拷贝,需要手工编写构造函数 Name obj3("obj3"); obj1 = obj2 = obj3; //调用等号运算符重载 cout


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有