一些运算符重载研究

一些运算符重载研究

#include <iostream>
  
/* 可重载运算符
双目算术运算符  + (加),-(减),*(乘),/(除),% (取模)
关系运算符  ==(等于),!= (不等于),< (小于),> (大于),<=(小于等于),>=(大于等于)
逻辑运算符  ||(逻辑或),&&(逻辑与),!(逻辑非)
单目运算符  + (正),-(负),*(指针),&(取地址)
自增自减运算符  ++(自增),--(自减)
位运算符    | (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移)
赋值运算符  =, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>=
空间申请与释放  new, delete, new[ ] , delete[]
其他运算符  ()(函数调用),->(成员访问),,(逗号),[](下标)
*/

template<typename T>
class A {
public:
    // C++类的隐式类型转换运算符operator type()
    operator int() const ;

    // 单目运算符,++a
    A& operator++() ;

    // 单目运算符,--a
    A& operator--() ;

    // 单目运算符,a++, “int++右”
    A operator++(int) const;

    // 单目运算符,a--, “int++右”
    A operator--(int) const;

    // 函数运算符重载
    void operator()() ;

    // 函数运算符重载,可带参数
    void operator()(int x) ;

    // 重点理解下面[]、*、->、&,作用于指针还是对象,返回类还是内部成员,是否const
    // 对于[],这两中形式是正确的,已经参考网络相关例子。
    // 必须这么写,参数也要有
    char& operator[](size_t) ;
    // 必须这么写,参数也要有,用于const
    char operator[](size_t) const ;

    // 说明:->和*根据具体情况,在智能指针中两者均为非const。已经参考网络一些例子。
    // 成员访问运算符重载,语句 p->m 被解释为 (p.operator->())->m
    T* operator->() ;
    // 提供const版本,智能指针也提供了
    const T* operator->()const;

    // 单目运算符,表示*a.
    T& operator*() ;
    // 提供const版本,智能指针也提供了
    T operator*()const;

    // 这两种形式是默认的类成员函数。
    // 取地址运算符,表示&a
    A* operator&() ;
    // 取地址运算符const,表示&a
    const A* operator&() const ;

    // 双目运算符,表示a+b
    A operator+(const A&) const ;

    // 双目运算符,表示a-b
    A operator-(const A&) const ;

    // 双目运算符,表示a*x
    A operator*(const A&) const ;

    // 双目运算符,表示a*x
    A operator/(const A&) const ;

    // 一元+,表示正
    A operator+() const ;

    // 一元-,表示负
    A operator-() const ;

    // 拷贝构造函数
    A& operator=(const A&) ;

    // 表示a+=b,返回引用可连等
    A& operator+=(const A&) ;

/*
    A& operator=(A&&) ;
*/
private:
    char* m_data;
    size_t m_len;
};

// new重载的三种方式,同步对应delete和[]
struct B {
    // 普通版本,抛异常
    // void* operator new(size_t) throw(std::bad_alloc);
    void* operator new(size_t);
    // 不抛异常的版本
    void* operator new(size_t, const std::nothrow_t&) noexcept;
    // placement new版本
    void* operator new(size_t, void*) noexcept;
};

int main() {

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值