1.運算符重載:
運算符重載,就是對已有的運算符重新進行定義,賦予其另一種功能,以適應不同的數據類型。對於基本數據類型,+號這種運算符,是認識的,但是對於我們新建的這些類,他們是不認識的,所以我們需要進行運算符的重載。
運算符重載(operator overloading)只是一種”語法上的方便”,也就是它只是另一種函數調用的方式。
語法: 定義重載的運算符就像定義函數,只是該函數的名字是operator@,這裏的@代表了被重載的運算符。函數的參數中參數個數取決於兩個因素。
- 運算符是一元(一個參數)的還是二元(兩個參數);
- 運算符被定義爲全局函數(對於一元是一個參數,對於二元是兩個參數)還是成員函數(對於一元沒有參數,對於二元是一個參數-此時該類的對象用作左耳參數)
示例代碼:
class person
{
public:
person(){}
person(int a,int h):age(a),height(h){}
int age;
int height;
// person operator+(person &m)
// {
// person tmp;
// tmp.age = this->age+m.age;
// tmp.height = this->height+m.height;
// return tmp;
// }
person operator+(person m)
{
person tmp;
tmp.age = this->age+m.age;
tmp.height = this->height+m.height;
return tmp;
}
};
//全局函數的方式進行運算符重載
// person operator+(person &m,person &n)
// {
// person tmp;
// tmp.age = m.age+n.age;
// tmp.height = m.height+n.height;
// return tmp;
// }
3.左移運算符重載:
ostream & operator<<(ostream &cout,person &p)
{
cout <<p.age<<p.height<<endl;
return cout;
}
//返回值爲引用,主要是爲了實現cout <<"hello"<"zww"<<endl; 這樣的形式,返回值不爲引用的話,那麼的話只能cout << p;
4.前置++和後置++ 運算符重載:
通過佔位參數來判斷前置還是後置:
person & operator++()
{
this->age++;
this->height++;
return *this;
}
person operator++(int)
{
person tmp;
tmp = *this;
this->age++;
this->height++;
return tmp;
}
5.智能指針:
class person
{
public:
person(int age)
{
this->m_Age = age;
}
void showAge()
{
cout << "年齡爲:" << this->m_Age << endl;
}
~person()
{
cout << "Person的析構調用" << endl;
}
int m_Age;
};
class smartpointer
{
public:
smartpointer(person *p)
{
this->p = p;
}
~smartpointer()
{
cout <<"智能指針西溝"<<endl;
if(this->p != NULL)
{
delete this->p;
this->p = NULL;
}
}
person & operator*()
{
return *this->p;
}
person* operator->()
{
return this->p;
}
private:
person* p;
};
int main()
{
person *p1 = new person(10);
smartpointer pointer(p1);
//pointer->showAge();
(*pointer).showAge();
}
6.賦值運算符重載:
一個類默認創建 默認構造、析構、拷貝構造 operator=賦值運算符 進行簡單的值傳遞 ,這個和深拷貝和淺拷貝類似,因爲=賦值運算符只會簡單的值拷貝,容易出問題,所以有時候我們需要 自己去寫一個賦值運算符重載。
class Person2
{
public:
Person2(char * name)
{
this->pName = new char[strlen(name) + 1];
strcpy(this->pName, name);
}
//重載 = 賦值運算符
Person2& operator= ( const Person2 & p)
{
//判斷如果原來已經堆區有內容,先釋放
if (this->pName != NULL)
{
delete[] this->pName;
this->pName = NULL;
}
this->pName = new char[strlen(p.pName) + 1];
strcpy(this->pName, p.pName);
return *this;
}
~Person2()
{
if (this->pName != NULL)
{
delete[] this->pName;
this->pName = NULL;
}
}
char * pName;
};
void test02()
{
Person2 p1("狗蛋");
Person2 p2("狗剩");
Person2 p3("");
p3 = p2 = p1;
cout << p2.pName << endl;
cout << p3.pName << endl;
}
主要是學習了運算符重載,運算符重載主要是爲了,對已有的運算符重新進行定義,賦予其另一種功能,以適應不同的數據類型。