重载操作符与转换
来源:互联网 发布:ipad网络不稳定 编辑:程序博客网 时间:2024/05/22 15:48
重载操作符是具有特殊名称的函数:保留字operator后接需定义的操作符符号。
重载操作符必须具有一个类类型的操作数
重载操作符的优先级和结合性是固定的
重载操作符不具备短路求值特性
当重载操作符作为成员函数时,其隐含的this指针限定为第一个操作数,一般将赋值操作符定义为成员函数,算术和关系操作符定义为友员函数。=,[], ->,()一般只能定义为成员函数,改变对象状态如自增,自减,解引用一般定义为成员函数, +=一般定义为成员函数,对称的运算符一般定义为非成员函数。
编译器会自动合成赋值操作符,取地址操作符,逗号操作符的默认版本
一个例子:
#pragma once#include <string.h>#include <string>#include <iostream>class MyString{public: MyString(const char *str = NULL); MyString(const MyString &rhs); MyString & operator=(const MyString &rhs); virtual ~MyString(void); MyString & operator+=(const MyString &rhs); friend std::ostream & operator <<(std::ostream &os,const MyString &s); friend std::istream & operator >>(std::istream &is,MyString &s);private: char *m_data; //std::string str;};MyString operator+(const MyString &,const MyString &);#include "MyString.h"MyString::MyString(const char *str){ if (str == NULL) { m_data = NULL; return; } m_data = new char[strlen(str) + 1]; strcpy(m_data,str);}MyString::~MyString(void){ delete []m_data; m_data = NULL;}MyString::MyString(const MyString &rhs){ m_data = new char[strlen(rhs.m_data) + 1]; strcpy(m_data,rhs.m_data);}MyString & MyString::operator=(const MyString &rhs){ if (this == &rhs) { return *this; } delete []m_data; m_data = new char[strlen(rhs.m_data) + 1]; strcpy(m_data,rhs.m_data); return *this;}MyString & MyString::operator+=(const MyString &rhs){ char *temp=m_data; int len = strlen(m_data) + strlen(rhs.m_data); temp = new char[len + 1]; if(!temp) { return *this; } strcpy(m_data,temp); strcat(m_data,rhs.m_data); delete[] temp; return *this; }std::ostream & operator <<(std::ostream &os,const MyString &s){ os << s.m_data; return os;}std::istream & operator >>(std::istream &is,MyString &s){ is >> s.m_data; if (is) { }else { s.m_data = NULL; } return is;}MyString operator+(const MyString &str1,const MyString &str2){ MyString str(str1); str += str2; return str;}
转换操作符,转换操作符的格式
operator type();
如: operator int(){return 0;}
转换操作符必须是成员函数,没有返回值,形参为空
函数调用操作符必须为成员函数
bool operator()(int a){return a > 0;}
阅读全文
0 0
- 重载操作符与转换
- 重载操作符与转换
- 重载操作符与转换
- 重载操作符与转换
- 重载操作符与转换(1)
- 第十四章:重载操作符与转换
- 第十四章 重载操作符与转换
- C++ primer:重载操作符与转换
- Chapter 24.重载操作符与转换
- 第十四章 重载操作符与转换
- [C++ Primer] 重载操作符与转换
- C++ 重载操作符与转换
- 重载转换操作符
- 转换操作符重载
- 重载操作符operator()与用户自定义类型转换
- C++复习 14 重载操作符与转换
- 第14章 重载操作符与转换
- C++ Primer笔记(14) 重载操作符与转换
- 自适应图像降噪滤波器的设计与实现
- 51 Nod 1006 最长公共子序列Lcs
- Python Map()方法的用法
- Android 开发之 Splash 页面 3 秒跳转
- LEADTOOLS Multimedia SDK更新:改进RTSP和H.265/H.264的硬件加速
- 重载操作符与转换
- 【OpenCV入门教程之八】线性邻域滤波专场:方框滤波、均值滤波与高斯滤波
- OSGB 文件格式
- springboot入门
- 选择排序
- SDL2.0 多线程使用信号量
- Java 中的一种更轻松的函数式编程途径
- 工具网站
- 错误处理技术