開門見山:在C++種只能在類內實現的運算符重載的只有四個,賦值運算符= 函數調用運算符() 下標運算符[] 指針訪問類成員的運算符->
第一種:賦值運算符=的重載
首先我們需要知道的是,一個類如果什么都沒有,系統會為這個類默認提供四種東西
1.無參構造函數(無參且函數體是空的)
2.析構函數(無參,且函數體是空的)
3.默認拷貝構造函數,對屬性進行值拷貝
4.賦值運算符的重載 operator=, 對屬性進行值拷貝(也就是說,在我們實際重載之前,編譯器以及寫過一個值拷貝的構造函數了)
通常我們都知道前三個,那么第四個就可以解釋為什么賦值運算符只能在類內進行重載了,因為如果是普通變量的普通類,那么系統提供的默認賦值函數是足夠的,但是如果涉及指針的變量,就需要我們自定義賦值函數了(避免同一個指針地址同時作為兩個類對象的成員數據,當其中一個被析構時,另一個對象報錯的現象)
//賦值運算符重載 class Student { public: Student(string a,int b):name(a),id(b) {} void Getname() { cout << this->name << endl; } void Getid() { cout << this->id << endl; } Student& operator=(Student& s) { name = "default"; id = 000; return *this; } private: string name; int id; };
int main() { Student s1("a", 1); Student s2("b", 2); s2 = s1; s2.Getid(); s2.Getname(); return 0; }
類外重載直接報錯:
第二種:下標運算符[]
下標運算符[]之所以要用類內進行重載的原因在於,[]必須要用一個對象,比如a[i],b[j]等等,針對對象的取下標操作,如果是全局的話,[3]就顯的毫無意義
//下標運算符[]重載 class Student { public: Student(string a,int b):name(a),id(b) {} void Getname() { cout << this->name << endl; } void Getid() { cout << this->id << endl; } Student operator[](int x) { Student sub("default",000); return sub; } private: string name; int id; }; int main() { Student s1("a", 1); Student s2("b", 2); s1 = s2[1]; s1.Getid(); s1.Getname(); return 0; }
第三種:函數調用運算符()
//函數調用運算符()重載 class Student { public: Student(string a,int b):name(a),id(b) {} void Getname() { cout << this->name << endl; } void Getid() { cout << this->id << endl; } Student operator()(string a, int b,int c) { name = a; id = b + c; return *this; } private: string name; int id; }; int main() { Student s1("a", 1); Student s2("b", 2); s2 = s1("b", 1, 2); s2.Getid(); s2.Getname(); return 0; }
第四種:指針訪問類成員運算符
由於是用於指針訪問類成員,因此->的重載必須是在類內完成的,不能夠使用全局的重載