运算符重载

运算符重载:是把运算符的操作数扩展到类对象上
运算符重载有两种形式:
成员函数形式、普通函数形式
成员函数形式一般般语法形式:
返回类型 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;
}

运算符重载需要注意以下几点:

  1. 只能重载已有的运算符,不能创造新的运算符.
  2. “.”, “.*”, “::”, "?:"不能重载.
  3. 重载运算符时,如果其所有操作数都是内置类型,则不能重载.
  4. “=”,"[]","->","()"只能以成员形式重载.
  5. 重载运算符不会改变运算符三特性.
  6. 单目运算符:
    a.成员形式,无参,唯一操作数传给this.
    b.普通函数,单参,唯一操作数传给参数.
    双目运算符:
    a.成员形式,单参,左操作数传给this,右操作数传给参数.
    b.普通函数,双参,左操作数传给第一参数, 右操作数传给第二参数.
    7*. 重载运算符尽可能保证所作操作和原运算符功能一致或相近 (建议)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值