运算符重载:
-
引出和目的
函数的重载,表现形式就是一名多用,同一个名字实现多个相近功能的函数。
+-*/=
这些基本的加减乘除对于C++中的基本类型是够用了,也不用我们在自定义的去重载。但是,在使用的类类型时,就有必要了。因为我们要重载这些运算符使之能达到我们自定义的功能。 -
运算符重载举例:
在对象的赋值与复制及拷贝构造函数中:说明了,在其中的第③个知识点:对象赋值的注意事项中,当跳出test函数的作用域之后程序就崩溃了。原因就是 stud_1 和 stud_2 两个对象公用 p_name 指针指向的名字空间了。导致在对象结束调用析构函数释放 p_name 所指向的内存空间的时候,被释放了两次,所以才会崩溃报错,在此我们来寻求一下解决办法——利用重载=
等号运算符。 -
举个代码栗子:
运算符的重载实际上就是函数的重载,即,定义一个重载运算符的函数。使指定的运算符不仅能实现原有的功能,而且在函数中还能实现新的自定义的功能,栗子如下://CStudent类的实现: class CStudent{ public: char* p_name; char sex; int no; int age; CStudent(); CStudent(char* t_name, char t_sex, int t_no, int t_age); ~CStudent(); CStudent& operator=(const CStudent& stud); }; CStudent::CStudent(char* t_name, char t_sex, int t_no, int t_age) :sex(t_sex), no(t_no), age(t_age) { int n_len = strlen(t_name); p_name = new char[n_len+1]; memset(p_name, 0, n_len+1); strcpy(p_name, t_name); cout << p_name<<"\t初始化完成"<<endl; } CStudent::CStudent() { cout <<"\t初始完成"<<endl; //注意我们在此处是不能使用p_name的,如: // cout <<p_name<<"\t初始完成"<<endl;这样会导致初始化失败或者对象复制时异常退出 //【望大佬指点迷津】 } CStudent::~CStudent() { cout <<p_name<< "\t~CStudent()"<<endl; if(p_name) { delete [] p_name; } } /* <返回类型说明符> operator <运算符符号>(<参数表>) { <函数体> } */ 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; no = stud.no; age = stud.age; return *this; } //test函数: void test() { CStudent stud1("王龙",'M',1101,21); CStudent stud2; stud2 = stud1; cout<<"stud2.name:"<<stud2.p_name<<endl; } //main主函数: int main() { test(); return 0; }
-
重载运算符的规则:
①. C++不允许用户自己定义新的运算符,只能对已有的C++运算符进行重载:
例如,在VB中使用**
运算符,例如:3**5
,表示3的5次方,如果你想在C++中创建**
运算符并实现重载,那是不行的。②. C++允许与不允许重载的运算符如下图:
③. 重载运算符不能改变运算符操作对象的个数:例如 > 和 < 运算符,本身是比较用的双目运算符,也就是说要有2个操作数,如果你重载完了之后变成不是2了,那肯定不行;
④. 重载运算符不能改变运算符的优先级别,乘除 */
运算符的优先级别大于+-
,如果你重载完了之后导致优先级改变了,那肯定也不行;
⑤. 重载运算符不能改变运算符的结合性,例如,赋值运算符=是从右向左开始结合的,如果你重载完了之后导致从左往右了,那肯定也不行;
⑥. 重载运算符的函数不能有默认的参数:不然就改变了运算符参数的个数,与第③点矛盾了;
⑦. 重载运算符的函数参数至少有一个是本类的对象或引用,不能全部都是C++的基本类型,例如:CStudent& CStudent::operator+(int a, int b)
这种也是不行的;
⑧. 重载运算符应该遵循运算符原有的含义,不能把+重载之后变成-的功能,虽然语法上没有错误,但是违背了重载运算符的初衷。