In addition to overloading functions, C + + allows you to define existing operators so that they can be used as processing data by operator overloading.
A code first.
1#include <iostream>2 using namespacestd;3 4 classNum5 {6 Public:7Num () {n=1;}8~num () {}9 int Get()Const{returnN;}Ten void Set(intx) {n=x;} One Private: A intN; - }; - the intMain () - { - num i; -Cout<<i.Get() <<Endl; +i++; - return 0; +}View Code
Compiling will prompt an error:
--------------------Configuration:demo1-win32 Debug--------------------
Compiling ...
Demo.cpp
E:\CCDEMO\demo1\demo.cpp: Error c2676:binary ' + + ': ' Class num ' does not define this operator or a conversion to a T Ype acceptable to the predefined operator this operator is not overloaded with this class without overloading + +;
An error occurred while executing cl.exe.
Demo1.exe-1 error (s), 0 warning (s)
Place code: i++ Comment, compile is successful; How to solve the above problem, we can use a function to solve, 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 what we call the C + + overloaded operator; The following operator overloads are used:
1#include <iostream>2 using namespacestd;3 4 classNum5 {6 Public:7Num () {n=1;}8~num () {}9 int Get()Const{returnN;}Ten void Set(intx) {n=x;} One voidAdd () {+ +N;} A void operator+ + () {++n;}//overloaded operators are used here - Private: - intN; the }; - - intMain () - { + num i; -Cout<<i.Get() <<Endl; + I.add (); ACout<<i.Get() <<Endl; at++i;//Use the + + operator here -Cout<<i.Get() <<Endl; - return 0; -}View Code
All right. Compile it, no problem. This is the simplest operator overload.
C + + Learning overloaded operators 1