class A
{
private:
int c[10];
public:
int &operator[](int i)
{
return c[i];
}
};
class B
{
A a[10];
public:
int &operator[](int i)
{
return a[i];
}
};
int main()
{
B b;
b[2]=5;
return 0;
}
In your code, a is not a single object A containing 10 integers, but an array of 10 As. Thus a[i] does not call the operator overloaded for A, but simply returns the ith value in that array. I'm not sure what you intended to do. Either remove the '[10]' from declaration of member 'a' or add another set of []s to the operator [] in B (make it "return a[0][i]" or something like that).
class A
{
friendclass B;
private:
int c[10];
public:
int &operator[](int i)
{
return c[i];
}
};
class B
{
A a[10];
public:
int &operator[](int i)
{
return a[i].c[i]; // change here
}
};
int main()
{
B b;
b[2]=5;
return 0;
}
in class B :
1 2 3 4
int &operator[](int i)
{
return a[i].c[i]; // change here
}
if you want return int you must set you index or you can return address of array in A::c but you must change return type to int * and write return a[i].c;
but if you want return type of A you must change type to A in operator [] but you cant write in main function b[2] = 5; its wrong!!!
class A
{
private:
int c[10];
public:
int &operator[](int i)
{
return c[i];
}
};
class B
{
A a[10];
public:
int &operator[](const pair<int, int> &index)
{
return a[index.first][index.second];
}
};
int main()
{
B b;
b[make_pair(2, 3)]=5;
return 0;
}
class A
{
private:
int c[10];
public:
int &operator[](int i)
{
return c[i];
}
};
class B
{
A a[10];
public:
A &operator[](int i)
{
return a[i];
}
};
int main()
{
B b;
b[2][3]=5;
return 0;
}