繁体   English   中英

C ++重载运算符[]

[英]C++ overloading operator[]

我如何重载operator[]以使其返回b[i]但作为类C的对象ob2的一部分? 我试着做一个朋友methot,但没有成功。

(主要任务是在不更改主类的情况下更正代码并使之正常工作)

#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
class C : public A, public B
{
public:
//...
   int operator []( int i ) const
   {
      return b[i];
   }

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

或者,您可以使用已经在类B中定义的运算符。只能按照与我为类C所示的运算符定义相同的方式正确定义它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM