重载操作符是具有特殊名称的函数:保留字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;}