Sirius' blog Sirius' blog
首页
  • 学习笔记

    • 《C++》
    • 《MATLAB》
    • 《Python》
  • 学习笔记

    • 《Git》
    • 《CMake》
  • 技术文档
  • 博客搭建
  • 学习
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Sirius0v0

怕什么真理无穷,进一寸有一寸的欢喜
首页
  • 学习笔记

    • 《C++》
    • 《MATLAB》
    • 《Python》
  • 学习笔记

    • 《Git》
    • 《CMake》
  • 技术文档
  • 博客搭建
  • 学习
  • 友情链接
关于
收藏
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • 基础

    • 程序的内存模型
    • CC++指针
    • CC++引用
    • CC++类与对象
    • CC++运算符重载
      • 加号运算符重载
      • 左移运算符重载
      • 递增运算符重载
      • 赋值运算符重载
      • 关系运算符重载
      • 函数调用运算符重载
    • CC++继承
    • CC++多态
    • CC++文件操作
  • Cpp小记
  • C++学习笔记-220705-V1
  • 进阶

  • 奇思妙用

  • 库的使用

  • 《C++》学习笔记
  • 基础
Sirius0v0
2023-07-06
目录

CC++运算符重载

# C/C++: 运算符重载

# 加号运算符重载

成员函数重载+

class Person
{
public:
    Person operator+ (Person &p)
    {
        Person temp;
        temp.m_A = this->m_A + p.m_A;
        temp.m_B = this->m_B + p.m_B;
        return temp;
    }
    
    int m_A;
    int m_B;
};

全局函数重载+

Person operator+ (Person &p1, Person &p2)
{
    Person temp;
        temp.m_A = p1.m_A + p2.m_A;
        temp.m_B = p1.m_B + p2.m_B;
        return temp;
}

成员函数重载本质调用为:

Person p3 = p1.operator+(p2);

全局函数重载本质调用为:

Person p3 = operator+(p1, p2);

以上均可简化为Person p3 = p1 + p2

# 左移运算符重载

如想实现对自定义类的输出,在重载<<时发现如重载函数void operator<< (cout),简化版本则成了p << cout,与预期不符,因而利用全局重载实现。

ostream& operator<< (ostream &cout, Person &p)
{
    cout << p.m_A << p.m_B << endl;
    return cout;
}

# 递增运算符重载

class MyInt
{
public:
    MyInt():num(0){};
    
    // 重载前置++运算符
    // 注意要返回引用,不然多次递增运算会发生错误
    MyInt& operator++ ()
    {
        num++;
        return *this;
    }
    
    // 重载后置++运算符
    // 区分后置++需要添加int做占位符,只能填int
    // 注意要返回值而不是引用,因为返回的是局部变量,返回引用后的操作将变得非法
    MyInt operator++(int)
    {
        MyInt tmp = *this;
        num++;
        return tmp;
    }
    
private:
    int num;
};
    
ostream& operator<< (ostream &cout, MyInt myint)
{
    cout << myint.num;
    return cout;
}

# 赋值运算符重载

注意事项:在自定义类中存在在堆中开辟的变量时,编译器自动提供的赋值运算符仅做了浅拷贝操作,存在重复释放内存的风险,需要自己重载赋值运算符。

Person& operator=(Person &p)
{
    // 影响判断变量是否在堆区
    if (m_Age != NULL)
    {
        delete m_Age;
        m_Age = NULL;
    }
    // 深拷贝
    m_Age = new int(*p.m_Age);
    
    return *this;
}

# 关系运算符重载

bool operator==(Person &p);

# 函数调用运算符重载

  • 重载后使用方式非常像函数的调用,因此称为仿函数;
class MyAdd
{
public:
    int operator()(int a, int b)
    {
        return a+b;
    }
};

使用:

MyAdd add;
int res = add(1,2);

// 使用匿名函数对象
cout << MyAdd()(1,2) << endl;
编辑 (opens new window)
#Cpp
上次更新: 2023/08/09, 13:21:24
CC++类与对象
CC++继承

← CC++类与对象 CC++继承→

最近更新
01
ipopt优化库配置及使用
07-21
02
ubuntu离线安装包的方法
07-21
03
其它控件的使用
03-05
更多文章>
Theme by Vdoing | Copyright © 2020-2024 Sirius0v0 | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式