Overloading of array operators (28)

Source: Internet
Author: User

After learning the string object, we could not help but have a question in mind: Does the string object also have the flexibility of C-mode strings? Is it possible to access a single character directly? Then the string class maximizes the compatibility of C strings, and can use string objects in a way that uses C strings.

Down we use the string class in C to see the sample code

#include <iostream> #include <string>using namespace Std;int main () {string s = "a1b2c3d4e";        int n = 0;        for (int i=0; i<s.length (); i++) {if (IsDigit (S[i])) {n++;        }} cout << n << Endl; return 0;}

Our program is used to count the number of numbers in a string, and to see the results of the compilation

Try it again with BCC compilation


It's also 4, try it again with the VS compiler.

VS is also 4, proving that this is no coincidence. So the question is, how do the objects of the class support the array's subscript access? Then we need to overload the array access operator. Array accessors are built-in operators in C/s + +, and the native meaning of array accessors is array access and pointer operations.

We'll review the pointers and arrays that we learned in C.

#include  <iostream> #include  <string>using namespace std;int main () {     int a[5] = {0};        for (int i =0; i<5; i++)     {        a[i] =  i;    }        for (int i=0; i<5 ;  i++)     {        cout << * ( A + i)  << endl;    // cout << a[i]  << endl;    }        cout <<  endl;        for (int i=0; i<5; i++)      {        i[a] = i + 10;     }&nBsp;       for (int i=0; i<5; i++)      {        cout << * (I + a)  <<  endl;    // cout << a[i] << endl;     }        return 0;}

Let's look at the compilation results

Access to the array has been implemented. So, let's talk about some of the knowledge points about the array access operator ([]):a> can only be overloaded with a member function of a class;b> overloaded functions can and can use only one parameter;c> to define multiple overloaded functions with different parameters.

Let's look at the example code to see how overloaded array access operators are implemented

#include  <iostream> #include  <string>using namespace std;class Test{  &NBSP;&NBSP;&NBSP;INT&NBSP;A[5];p ublic:    int& operator []  (int i )     {        return a[i];     }        int& operator []  (const string & s)     {        if ( s ==  "1st"  )         {             return a[0];        }         else if ( s ==  "2nd"  )          {            return a[1];    &nbSp;    }        else if ( s ==  "3rd"  )         {             return a[2];        }         else if ( s ==  "4th"  )          {            return a[3];         }        else if (  s ==  "5th"  )         {             return a[4];         }                return  a[0];  &nbsP; }        int length ()     {         return 5;    }};int main () {     test t;        for (int i=0; i< T.length ();  i++)     {        t[i] =  i;    }        for (int i=0; i< T.length ();  i++)     {        cout < < t[i] << endl;    }         cout << endl;        cout << t[" 5th "] << endl;    cout << t[" 4th "] << endl ;     cout << t["3rd"] << endl;    cout << t["2nd"]  << endl;    cout << t["1st"] << endl;         return 0;}

By overloading the array operator, we can access the class object in C + + in the same way that the array can be used. We can also access the array directly via t["1st". Look at the compilation results

We use the overload of the array operator to refine the array class we implemented earlier


IntArry.h Source

#ifndef _intarray_h_#define _intarray_h_class intarray{private:int m_length;        int* M_pointer;    Intarray (int len);    BOOL Construct ();p ublic:static intarray* newinstance (int length);    int length ();    BOOL Get (int index, int& value);    BOOL Set (int index, int value);    int& operator [] (int index);    intarray& self (); ~intarray ();}; #endif



IntArray.cpp Source

#include   "IntArray.h" Intarray::intarray (Int len) {    m_length = len;} Bool intarray::construct () {    bool ret = true;         m_pointer = new int[m_length];         if ( m_pointer )     {         for (int i=0; i<m_length; i++)         {             m_pointer[i] = 0;         }    }    else     {        ret = false;    }         return ret;} Intarray* intarray::newinstance (int length) {    intarRay* ret = new intarray (length);         if ( ! ( Ret && ret->construct ())  )     {         delete ret;                 ret = 0;    }         return ret;} Int intarray::length () {    return m_length;} Bool intarray::get (int index, int& value) {    bool ret =   (0 <= index)  &&  (Index <= length ());         if ( ret )     {         value = m_pointer[index];    }         return ret;} bool  Intarray::set (Int index, int value) {    bool ret =  (0  <= index)  &&  (Index <= length ());         if ( ret )     {        m_ pointer[index] = value;    }         Return ret;} int& intarray::operator []  (int index) {    return m_pointer[ index];} Intarray& intarray::self () {    return *this;} Intarray::~intarray () {    delete[] m_pointer;}


Test.cpp Source

#include  <iostream> #include  <string> #include   "IntArray.h" using namespace  Std;int main () {    intarray* a = intarray::newinstance (5);             if ( a != NULL )      {        intarray& array = a->self () ;                cout  <<  "Array.Length ()  = "  << array.length ()  << endl;             array[0] = 1;                 for (int i=0; i< Array.Length ();  i++)         {               cout << array[i] << endl;         }    }        delete a;         return 0;}

We have added two functions in the IntArray.h header file, one is an overload of the array operator, and the other is a reference to the return class. The return class reference is convenient for us to access the array directly in the test.cpp to see how the results of the compilation

Through the study of the overload of the array operator, it is summarized as follows:1, the String class is compatible with the use of the C string, 2, the overload of the array accessor allows the object to simulate the behavior of the array, 3, the array accessor can be overloaded only by the member function of the class, 4, the overloaded function can only use one parameter.


Welcome Everybody to learn C + + language together, can add me qq:243343083.

Overloading of array operators (28)

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.