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;
}
主要是学习了运算符重载,运算符重载主要是为了,对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。