C++重载操作符笔记
来源:互联网 发布:会员制软件 编辑:程序博客网 时间:2024/06/04 18:53
重载和多态是不一样的,重载主要作用是多操作符号的重载。(Operator overloading)
如有下面的类:
class complex { // very simplified complexdouble re, im;public:complex(double r, double i) :re{r}, im{i} { }complex operator+(complex);complex operator*(complex);};
要实现其中的+和*操作,就必须自定义其函数功能,也就是重载了编译器原有的+和*操作。
void f(complex a, complex b){complex c = a + b; // shor thandcomplex d = a.operator+(b); // explicit call}
下面操作符都是可以重载的:
注意其重载的参数不能出错:
class X {public: // members (with implicit this pointer):X∗ operator&(); // prefix unary & (address of)X operator&(X); // binar y & (and)X operator++(int); // postfix increment (see §19.2.4)X operator&(X,X); // error : ter naryX operator/(); // error : unar y /};X operator−(X); //prefix unary minusX operator−(X,X); //binar y minusX operator−−(X&,int); // postfix decrementX operator−(); //error : no operandX operator−(X,X,X); // error : ter naryX operator%(X); // error : unar y %
操作符= (assignment), & (address-of), and , (sequencing) 都有预先定义的意义,但是可以利用deleted关键字去掉:
class X {public:// ...void operator=(const X&) = delete;void operator&() = delete;void operator,(const X&) = delete;// ...};void f(X a, X b){a = b; // error : no operator=()&a; // error : no operator&()a,b; // error : no operator,()}
操作符的重载参数必须有一个是用户自定义的数据类型,这样就保证了不可以修改原有操作符的作用。
日期数据类型重载++:
enum Day { sun, mon, tue, wed, thu, fri, sat };Day& operator++(Day& d){return d = (sat==d) ? sun : static_cast<Day>(d+1);}
如果是自定义的类,成员多,占内存大,那么就定义move operation会让传输速度加快。
Matrix operator+(const Matrix& a, const Matrix& b) // return-by-value{Matrix res {a};return res+=b;}
操作符如果是返回参数的其中一个对象的就通常是返回引用参数:
Matrix& Matrix::operator+=(const Matrix& a) // return-by-reference{if (dim[0]!=a.dim[0] || dim[1]!=a.dim[1])throw std::exception("bad Matrix += argument");double∗ p = elem;double∗ q = a.elem;double∗ end = p+dim[0]∗dim[1];while(p!=end)∗p++ += ∗q++return ∗this;}
单操作符!例子。
X operator!(X);struct Z {Z operator!(); //does not hide ::operator!()X f(X x) { /* ... */ return !x; } // invoke ::operator!(X)int f(int x) { /* ... */ return !x; } // invoke the built-in ! for ints};
- C++【操作符重载】
- c++::操作符重载
- C++:操作符重载
- 操作符重载——C/C++学习笔记
- (C/C++学习笔记操作符重载入门)
- C++(笔记)重载运算符简单合并操作
- 操作符重载(C++)
- C++-重载操作符<< >> = + - * /
- c++_操作符重载
- C++重载操作符笔记
- c++操作符重载笔记
- 【笔记-C++】 运算符重载
- C/C++: 操作符重载案例
- (C/C++学习笔记)操作符重载的两种方法
- C++操作符重载专题(C++)
- 类型转换和操作符重载 (c#)
- C++——操作符重载
- 重载操作符 (c++primer 4e)
- linux查看硬件常用命令小结(图文)
- LeetCode题解: Flatten Binary Tree to Linked List
- Struts的action自动装配到spring容器可能出现异常的解决方法
- contos oracle ORA-12162 TNS net service name is incorrectly specified
- 2013武科大蓝桥杯校内选拔赛 H题 火柴棒
- C++重载操作符笔记
- 滨州学院CSDN高校俱乐部第四期公开课——未来IT技术发展趋势及职业规划
- java对象序列化
- POJ 1287 Networking (mst简单)
- LeetCode题解: Longest Consecutive Sequence
- 配置vps主机安全
- 解决oracle11g ORA-00119 ORA-00132方法
- 重新安装mysql遇到问题小结
- View.VISIBLE、INVISIBLE、GONE的区别