就是改变原来运算符的一些性质,也就是给运算符重新定义它的功能。
例子:比如编译器自己形成的浅拷贝构造函数可能会导致析构函数引发内存多次释放而引起内存错误,那么归根到底是由于赋值操作出了问题,那么我们可以针对类,单独对“=”进行运算符重载,解决浅拷贝可能引发的问题。
class CSstudent{
public:
char* p_name;
char sex;
int age;
int num;
CStudent& operator=(const CStudent& stud);//重新定义=,即重载运算符=,此=只对CSstudent类起效果
}
CStudent& CStudent::operator=(const CStudent& stud) { if (p_name) { delete[] p_name; p_name = NULL; } int name_len = strlen(stud.p_name) + 1; p_name = new char[name_len]; memset(p_name, 0, name_len); strcpy(p_name, stud.p_name); sex = stud.sex; num = stud.num; age = stud.age; return *this; }