如何重載operator[]
使其返回b[i]
,但作爲C
類的對象ob2
的一部分?我試圖做一個朋友methot,但它沒有奏效。C++超載運算符[]
(主要任務是糾正代碼不改變主類,並使其工作)
#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
你可以改變什麼,你不能改變什麼? –
我可以重載操作符並在類中添加代碼,我不能改變主函數。 – user3308470