C++【操作符重载】
来源:互联网 发布:六边形战士 知乎 编辑:程序博客网 时间:2024/04/30 18:00
c1-(c2+c3)
c1.sub (c2.add (c3));
1.操作符和操作符函数
1)双目操作符:+-*/%...,+=/-=...,<</>>
L#R -> L.operator#(R),左调右参
-> ::operator#(L,R),左一右二
2)单目操作符:-/~/!...,++/--
#O/O# -> O.operator#()
-> ::operator#(O)
3)三目操作符:?:,不能表示为操作符函数
2.所谓操作符重载,其本质就是根据不同的数据类型,定义相应的操作符函数,以使自定义类型能够与基本类型应用相同或相近的语义进行运算。
3.能够被重载的操作符的操作数种至少有一个是类类型。
4.操作符的优先级和结合序不会因重载而发生变化。
5.操作符的操作数个数不会因重载而发生变化。
6.除了“()”操作符以外所有的操作符函数都不能带有缺省参数。
7.并不是所有的操作符都能重载。
8.不能发明新的操作符。x ** y是错的
补充:
int a=10,b=20;
注意(a+b)=30;编译是不通过的,因为a+b的结果是一个右值。或者说,是一个临时变量,无法作为左值去接收。
const Complex operator+(const Complex& c)const {
return Complex(m_r+c.m_r,m_i+c.m_i);
}
从左至右三个Const依次表示为:返回右值,支持常量右操作数,支持常量左操作数。
实例代码:
#include <iostream>
using namespace std;
class Complex {
public:
Complex (int r = 0, int i = 0) :
m_r (r), m_i (i) {}
void print (void) const {
cout << m_r << '+' << m_i << 'i' << endl;
}
// 从左到右三个const,依此表示:
// 返回右值
// 支持常量右操作数
// 支持常量左操作数
const Complex operator+ (const Complex& c) const{
return Complex (m_r + c.m_r, m_i + c.m_i);
}
private:
int m_r;
int m_i;
friend const Complex operator- (const Complex&,
const Complex&);
};
const Complex operator- (const Complex& cl,
const Complex& cr) {
return Complex (cl.m_r-cr.m_r, cl.m_i-cr.m_i);
}
int main (void) {
const Complex c1 (1, 2);
const Complex c2 (3, 4);
Complex c3 = c1 + c2;
// Complex c3 = c1.operator+ (c2);
c3.print (); // 4+6i
/*
int a = 10, b = 20;
(a + b) = 30;
*/
/*
Complex c4;
(c3 + c4) = c2;
*/
c3 = c2 - c1;
// c3 = ::operator- (c2, c1);
c3.print (); // 2+2i
return 0;
}
- C++【操作符重载】
- c++::操作符重载
- C++:操作符重载
- 操作符重载(C++)
- C++-重载操作符<< >> = + - * /
- c++_操作符重载
- C/C++: 操作符重载案例
- C++操作符重载专题(C++)
- 类型转换和操作符重载 (c#)
- C++——操作符重载
- 重载操作符 (c++primer 4e)
- 【C++】 重载操作符类编程
- 自定义数据类型,操作符重载实例[C#]
- C++primer读书笔记8-重载操作符
- C/C++ 之 操作符重载
- [c++]实例-类array,重载操作符
- C++,重载输出操作符<<, cout.operator()
- c++string类的操作符重载
- mysql 导入导出表数据
- .net利用ajax技术实现图片上传并回显到界面
- 认识JVM
- 一文教你看懂大数据的技术生态圈:Hadoop,hive,spark
- sql:添加或者删除唯一值约束,添加外键约束
- C++【操作符重载】
- boost::bind的使用
- 联想G510进入BIOS的两种方法
- Linux 进程间通信
- Lifetime Improvement of NAND Flash-based Storage Systems Using Dynamic Program and Erase Scaling
- 【高级算法】Lasvegas算法解决3SAT问题(C++实现代码)
- 无限级分类展示
- 生成树(treegrid)的数据格式
- sgu265:Wizards(计算几何)