C + + Learning overloaded operators 1

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.