C ++ learning heavy-duty operator 1, heavy operator
In addition to overload functions, C ++ Allows defining existing operators so that they can be used like processing data through Operator overloading.
Code first
1 # include <iostream> 2 using namespace std; 3 4 class num 5 {6 public: 7 num () {n = 1;} 8 ~ Num () {} 9 int get () const {return n;} 10 void set (int x) {n = x;} 11 private: 12 int n; 13 }; 14 15 int main () 16 {17 num I; 18 cout <I. get () <endl; 19 I ++; 20 return 0; 21}View Code
An error will be prompted during compilation:
------------------ Configuration: demo1-Win32 Debug --------------------
Compiling...
Demo. cpp
E: \ CCDEMO \ demo1 \ demo. cpp (19): error C2676: binary '++ ': 'class num' does not define this operator or a conversion to a type acceptable to the predefined operator. the following message is displayed, indicating that this class is not overloaded. ++ operator;
An error occurred while executing cl.exe.
Demo1.exe-1 error (s), 0 warning (s)
Compile the code by commenting on I ++. You can use a function to solve the problem. See the following code:
#include<iostream>using namespace std;class num{public:num(){n=1;}~num(){}int get() const{return n;}void set(int x){n=x;}void add(){++n;}private:int n;};int main(){num i;cout<<i.get()<<endl;i.add();cout<<i.get()<<endl;//i++;return 0;}
The above can solve the problem, but there is no reality we call the C ++ overload operator; the following uses the operator overload:
1 # include <iostream> 2 using namespace std; 3 4 class num 5 {6 public: 7 num () {n = 1;} 8 ~ Num () {} 9 int get () const {return n;} 10 void set (int x) {n = x;} 11 void add () {++ n ;} 12 void operator ++ () {++ n ;}// here, the overload operator 13 private: 14 int n; 15}; 16 17 int main () is used () 18 {19 num I; 20 cout <I. get () <endl; 21 I. add (); 22 cout <I. get () <endl; 23 ++ I; // use the ++ Operator 24 cout <I. get () <endl; 25 return 0; 26}View Code
Okay. Compile it. No problem. This is the simplest operator overload.