博客园  :: 首页  :: 新随笔  :: 管理

c++中的运算符重载operator2

Posted on 2020-01-02 00:44  wsg_blog  阅读(423)  评论(0编辑  收藏  举报

Index C++

c++中的运算符重载operator2

上一篇operator1中,大概说了下重载的基本用法,接下来对c++中常见的可重载运算符归一下类,说一下它们的返回值,讨论下较为复杂的运算符重载上的坑 🕳

首先看一下常见的重载原型

  • +-*/%^&|~ 原型:const T operatorX(const T& l, const T& r) const; //注意:返回值是const T 新对象不是引用,而且不能当左值(a+b=3 这是不被允许的)
  • !&&||< <= == >= > 原型:bool operatorX(const T& l, const T& r) const; //关系型运算符 返回值是bool
  • [] 原型:T& T::operator[](int index);

++ --运算符重载

//原型及部分实现
class Integer
{
public:
    ...
    const Integer& operator++();     //++a 返回值为a+1
    const Integer operator++(int);  //a++ 返回值为a 然后a=a+1 注意:返回值不是引用而是新的对象
    const Integer& operator--();     //--a 返回值为a-1
    const Integer operator--(int);  //a-- 返回值为a
};

//定义(实现)
const Integer& Integer::operator++()
{
    *this += 1;
    return *this;
}

const Integer Integer::operator++(int)
{
    Interger old(*this);  //拷贝构造
    ++(*this);
    return old;
}

[]运算符

最明显的例子就是vector,重载后的vector就可以进行扩展

class Vector //为了防止编译冲突我们改一下名字,第一个字母大写好了
{
public:
    Vector(int size):m_size(size)
    {
        m_array = new int[size];
    } 
    ~Vector() { delete m_array; }
    int& operator[](int index) { return m_array[index]; }
private:
    int m_size;
    int *m_array;
}

= 赋值运算符

这个也较复杂:复杂在哪呢,类之间的赋值有两种 一种是拷贝构造函数 一种是直接赋值

//=运算符重载原型定义
T& T::operator=(const T& rhs)
{
    //check for self assignment
    if( this!= &rhs)
    {
    //preform assignment
    }
    return *this;
}
MyType b;  //b走构造
MyType a=b;  //a走拷贝构造 拷贝构造不能重载
a=b;    //直接赋值 赋值可以被重载

看个=重载例子:

#include <iostream>
using namespace std;
class Cargo
{
public:
        Cargo& operator=(const Cargo& rhs)
        {
                cout << "inside Cargo::operator=()" << endl;
                if(this != &rhs)
                { cout << "处理不等问题"<< endl; }
                return *this;
        }
};
class Truck
{
        Cargo b;
};
int main()
{
        Cargo a;  //默认构造函数
        Cargo b=a;  //b对象实例化走的 拷贝构造函数
        b=a;    //=重载
        Truck c,d;
        c = d;  //=重载
        return 0;
}