C++學習筆記之運算符重載呢

運算符重載:
1.運算符重載,把運算符重新定義新的規則(例:之前運算符+的作用爲加但通過運算符重載的時候,就會把加變爲減或者其他意思,之後再調用‘+’號的時候,就會行使指定的意思
2.幾乎所有的運算符都可以被重載,除以下:::,?:,sizeof這些是不能被重載的
3.運算符重載基本上出現在類中和結構中。
4.運算符重載完後要滿足原來的運算規則
5.運算符其實也相當於函數的重載(就是調用函數名

運算符重載:operator<需要重載的符號>
運算符重載:以下程序中重載了運算符前++和後++
還有重載了-號和+號

#include<iostream>
using namespace std;
class Person
{
	public:
	int a;
	Person(int x)
	{
		a=x;
	}
	int fun(Person &p);
	{
		return this->a+p.a;
	}
	int operator+(const Person &p)//加const的原因是因爲爲了不改變參與對象的值
	{	
		return this->a+p.a;		
	}
	int operator-(const Person &p)
	{
		return this->a-p.a;
	}
	//加&,是爲了不調用拷貝構造,當前調用者並沒有消失,不需要拷貝
	//前加加
	Person &operator++()
	{
		this->a++;
		return *this;//把當前的對象返回出去
	}
	//後加加
	Person &operator++(int)
	{
		Person temp=*this;
		this->a++;//當前對象的值自增
		return temp;//把之前的值返回出去
	}
};
//用於對象和對象之間的操作的
int main()
{
	Person p1(10);
	Person p2(20);
	cout<<p1<<"\t"<p2<<endl;
	int c=p1+p2;//加法運算重載
	c=p2-p1;//減號運算重載
	++p1;//前加加運算重載
	//或者直接用+號就可以了
	++p1;
	cout<<c<<endl;
	cout<<p1.a<<endl;
	system("pause");
	return 0;
}

等號的運算符重載
什莫時候用到等號重載呢?
就是對象需要申請內存的寫的時候就需要等號重載
因爲一般的等號在由於對象給對象賦值的時候會報錯,因爲這裏涉及到了有指針指向同一地址的錯誤,一旦上一個對象用過後調用析構函數將內存釋放掉,那麼被賦值的對象會不知道指向哪裏,因此會導致錯誤的存在。

#include<iostream>
using namespace std;
class Person
{
	char *p;
public:
	Person()
	{
		p=NULL;
	}
	Person(char *str)
	{
		p=new char[strlen(str)+1];
		strcpy(p,str);
	}
	void fun()
	{
		cout<<p<<endl;
	}
	~Person()
	{
		if(p!=NULL)
		{
			delete[]p;
			p=NULL;
		}
	}
	Person &operator=(const Person&x)
	{
		//要賦值的對象裏面的指針是否有申請內存,有就釋放
		if(this->p!=NULL)
		{
			delete[]this->p;
			this->p=NULL; 
		}
		this->p=new char[strlen(x.p)+1];
		strcpy(this->p,x.p);
		return *this;
	}
};
void text()
{
	Person p1("lijiamin");
	Person p2;
	p2=p1;
	p1.fun();
	p2.fun();
}
int main()
{
	text();
	system("pause");
	return 0;
}

括號重載

#include<iostream>
using namespace std;
class Person()
{
public:
	void operator()(int a,int b)
	{
		cout<<"who l am"<<endl;
	}
};
int main()
{
	Person p1;
	p1(1,2);
	system("pause");
	return 0;
}

智能指針:用於託管new出來的對象,讓這個對象自動釋放內存,就是這個對象有着智能指針的作用。

#include<iostream>
using namespace std;
class Person
{
	int id;
public:
	Person(int x)
	{
		id=x;
	}
	~Person(){cout<<"析構了"<<endl;}
	void getID()
	{
		cout<<id<<endl;
	}
};
class smartPointer
{
	Person *p;//用於託管的指針
publicsmartPointer(Person *x)
	{
		p=x;
	}	
	~smartPointer()
	{
		if(p!=NULL)
		{
			delete p;
			p=NULL;
		}
	}
	//重載->
	Person *operator->()
	{
		return this->p;
	}
	//重載*
	Person& operator*()
	{
		return *this->p;
	}
};
void text()
{
	//智能指針像指針一樣去使用,即SP->,以及(*SP)解引用
	smartPointer sp(new Person(100));
	sp->getId();
	(*sp).getId();
} 
int main()
{
	text();
	system("pause");
	return 0;
}

本節內容之所以會有,原因是因爲對象和對象之間不能直接像變量一樣進行運算
因此,需要將運算符進行重載,將運算符的內容重新設計一下,從而能達到對象應用不出錯的程度。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章