一些运算符重载研究
#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;
}
这篇博客探讨了C++中的运算符重载,包括双目和单目运算符,以及关系、逻辑和位运算符。同时,还介绍了类模板中的隐式类型转换、自增自减、成员访问和指针运算符的重载。此外,文章涉及了内存管理,包括new和delete的重载,以及对智能指针操作的影响。
81

被折叠的 条评论
为什么被折叠?



