operator overloading
Customizes the C++ operators for operands of user-defined types.
std::addressof
std::addressof模板函数定义在<memory>头文件中,用于获取类或函数的真实地址,
即使在类重载了地址操作符&的情况下也能正常工作
原来c++可以重载运算符& ,当重载了运算符& 之后,要取地址就需要std::addressof 来获取地址了。
重载操作符
不能重载以下操作符:
sizeof ——sizeof操作符。
. ——成员操作符。
.* ——成员指针操作符。
:: ——作用域解析操作符。
?: ——条件操作符。
typeid—— 一个RTTI操作符。
const_cast ——强制类型转换操作符。
dynamic_cast ——强制类型转换操作符。
reinterpret_cast ——强制类型转换操作符。
static_cast ——强制类型转换操作符 基本类型能转换 但是不能转换指针类型
大多数操作符都可以通过成员或非成员函数进行重载,但是下面的操作符只能通过成员函数进行重载
= ——赋值操作符。
() ——函数调用操作符。
[] ——下表操作符。
-> ——通过指针访问类成员的操作符
函数说明-只有C++预定义的操作符才可以被重载重载操作符不能改变他们的操作符优先级;重载操作符不能改变操作数的个数
operator是C++的关键字,它和运算符一起使用,表示一个运算符函数
C++扩展运算符功能的方法
强制类型转换 强制类型转换运算符 <要转换到的类型> (待转换的表达式)
double d = static_cast <double> (3*5);
reinterpret_cast 用于进行各种不同类型的指针之间、不同类型的引用之间以及指针和能容纳指针的整数类型之间的转换。
转换时,执行的是逐个比特复制的操作
用 reinterpret_cast 可以将多态基类(包含虚函数的基类)的指针强制转换为派生类的指针,
但是这种转换不检查安全性,即不检查转换后的指针是否确实指向一个派生类对象。
dynamic_cast专门用于将多态基类的指针或引用强制转换为派生类的指针或引用,而且能够检查转换的安全性。对于不安全的指针转换,转换结果返回 NULL 指针
Derived & r = dynamic_cast <Derived &> (b);
const_cast 运算符仅用于进行去除 const 属性的转换,它也是四个强制类型转换运算符中唯一能够去除 const 属性的运算符
模板
template<typename T> void swap(T& t1, T& t2);
template <class T> class Stack
template <class T> Stack<T>::Stack(){
示例
/* Online C++ Compiler and Editor */
#include <iostream>
class nonaddressable
{
public:
typedef double useless_type;
private:
useless_type operator&() const;
};
template <class T>
T * addressof(T & v)
{
return reinterpret_cast<T *>(& const_cast<char&>(reinterpret_cast<const volatile char &>(v)));
}
int main()
{
nonaddressable na;
nonaddressable * naptr = (addressof)(na); // No more compiler error.
}
###说明
必须首先决定是将其声明为类的成员函数还是为一个普通的非成员函数
using namespace std;
error: call of overloaded ‘addressof(nonaddressable&)’ is ambiguous
error: call of overloaded ‘addressof(nonaddressable&)’ is ambiguous
编译器匹配到了stl_algobase.h里的copy函数,因为我传的参数std::vector::iterator(vec.begin())是属于namespace std的。
In C++11 the template std::addressof[1], in the <memory> header,
was added to solve this problem. Since C++17 the template is also marked constexpr.
解决的办法一:指定命名空间
解决的办法二:函数名用括号包住
操作符
: public:和private:后面的冒号,表示后面定义的所有成员都是公有或私有的,直到下一个"public:”或"private:”出现为止
:构造函数后面的冒号起分割作用,是类给成员变量赋值的方法,初始化列表,更适用于成员变量的常量const型。
: 类名冒号后面的是用来定义类的继承 class 派生类名 : 继承方式 基类名
继承方式:public、private和protected,默认处理是public。
参考
call of overloaded 'xxx' is ambiguous https://blog.csdn.net/dengshi1294/article/details/101869075/
More C++ Idioms https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms