运算符重载:是把运算符的操作数扩展到类对象上
运算符重载有两种形式:
成员函数形式、普通函数形式
成员函数形式一般般语法形式:
返回类型 operator 运算符(形参表)
{
函数体:
}
String& operator=(const String& ref)
{}
普通函数形式:
int operator+(const int& a, const int& b)
{
return a+b;
}
例:string类操作数的重载
#include<iostream>
#include<cstring>
using namespace std;
class String
{
private:
char* ps;
public:
String(char* p = "")
:ps(new char[strlen(p) + 1])
{
strcpy(ps, p);
cout << "String(char*)" << endl;
}
~String()
{
cout << "~String()" << endl;
delete[] ps;
ps = NULL;
//delete free close destory ...
}
String(const String& ref)
:ps(new char[strlen(ref.ps) + 1])
{
strcpy(ps, ref.ps);
cout << "String(const String&)" << endl;
}
//赋值重载
String& operator=(const String& ref)
{
if (this->ps != NULL)
{
delete[] this->ps;
this->ps = NULL;
}
this->ps = new char[strlen(ref.ps) + 1];
strcpy(this->ps, ref.ps);
return *this;
}
//+重载
String & operator+(String &ref)
{
String *temp = new String("");
temp->ps = new char[strlen(ps) + strlen(ref.ps) + 1];
strcpy(temp->ps, ps);
strcat(temp->ps, ref.ps);
return *temp;
}
//+=重载
String & operator+=(String &ref)
{
String *temp = new String("");
temp->ps = new char[strlen(ps) + strlen(ref.ps) + 1];
strcpy(temp->ps, ps);
strcat(temp->ps, ref.ps);
return *temp;
}
//==重载
bool operator==(const String&ref)
{
cout << (strcmp(ps, ref.ps) == 0)<<endl;
return (strcmp(ps, ref.ps) == 0);
}
//!=重载
bool operator!=(const String&ref)
{
cout << (strcmp(ps, ref.ps) != 0) << endl;
return (strcmp(ps, ref.ps) != 0);
}
//<
bool operator<(const String&ref)
{
cout << (strcmp(ps, ref.ps) < 0) << endl;
return (strcmp(ps, ref.ps) <0);
}
//<=
bool operator<=(const String&ref)
{
cout << (strcmp(ps, ref.ps) <= 0) << endl;
return (strcmp(ps, ref.ps) <= 0);
}
//>
bool operator>(const String&ref)
{
cout << (strcmp(ps, ref.ps) > 0) << endl;
return (strcmp(ps, ref.ps)>0);
}
//>=
bool operator>=(const String&ref)
{
cout << (strcmp(ps, ref.ps) >= 0) << endl;
return (strcmp(ps, ref.ps) >= 0);
}
//[]
char& String::operator[](int index)
{
return ps[index];
}
public:
void Show()const
{
cout << ps << endl;
}
};
int main()
{
String s1("haha");
String s2(s1);
return 0;
}
运算符重载需要注意以下几点:
- 只能重载已有的运算符,不能创造新的运算符.
- “.”, “.*”, “::”, "?:"不能重载.
- 重载运算符时,如果其所有操作数都是内置类型,则不能重载.
- “=”,"[]","->","()"只能以成员形式重载.
- 重载运算符不会改变运算符三特性.
- 单目运算符:
a.成员形式,无参,唯一操作数传给this.
b.普通函数,单参,唯一操作数传给参数.
双目运算符:
a.成员形式,单参,左操作数传给this,右操作数传给参数.
b.普通函数,双参,左操作数传给第一参数, 右操作数传给第二参数.
7*. 重载运算符尽可能保证所作操作和原运算符功能一致或相近 (建议)