user3308470
user3308470

Reputation: 107

C++ overloading operator[]

How can i overload operator[] to make it return b[i] but as a part of object ob2 of class C? I tried to do it as a friend methot but it didnt worked.

(The main task is to correct the code without changing main class and make it work)

#define MAX_CHAR  512

class A
{
protected:
    char str[MAX_CHAR];
public:
    A(char sstr[])
    {
        str[0] = '\0';
        try
        {
            strcpy_s(str, sizeof(str), sstr);
        }
        catch (bad_alloc)
        { }
    }
    void disp()
    {
        cout << str << endl;
    }
};

class B
{
protected:
    int* b;
public:
    B(int dim)
    {
        try
        {
            b = new int[dim];
            memset(b, 0, dim * sizeof(int));
        }
        catch (bad_alloc)
        { }
    }

    ~B()
    {
        if (b) delete[] b;
    }

    void disp()
    {
        if (b)
            for (size_t it = 0; it < _msize(b) / sizeof(b[0]); ++it)
                cout << b[it] << endl;
    }
    int& operator[](size_t dim)
    {
        return b[++dim];
    };
};


class C: public A, public B
{
public:
    C(int i, char sstr[])
        : A(sstr),
          B(i)
    { }
    friend ostream& operator<<(ostream& wyjscie, const C& ob);
};

ostream& operator<<(ostream& wyjscie, const C& ob)
{
    for (int i = 0; i < 10; i++)
        wyjscie << " i = " << *(ob.b) << " str = " << ob.str << endl;
    return wyjscie;
}

int main(int argc, char* argv[])
{
    C ob1(10, "abcde"), ob2(20, "efkjyklmn");
    for (size_t it = 0; it < 10; ++it)
    {
        ob2[it] = it * it + 1;
        cout << "ob[it] = " << ob2[it] << " it = " << it << endl;
    }
    cout << ob1 << endl << ob2 << endl;
    system("pause");
    //ob1 = ob2;
    //cout << endl << endl << ob1;
    //C ob3 = ob1;
    //cout << endl << endl << ob3;
    return 0;
}

#undef MAX_CHAR

Upvotes: 0

Views: 91

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

class C : public A, public B
{
public:
//...
   int operator []( int i ) const
   {
      return b[i];
   }

   int & operator []( int i )
   {
      return b[i];
   }
};

Or you can use the operator already defined in class B. Only it shall be defined correctly the same way as I have shown definitions of the operator for class C.

Upvotes: 1

Related Questions