Operator overloading

Can i overload the operator[] to return a reference when A's array of object as a member of B class...?

example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

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;
}

does it work????
Last edited on
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).
please put your code on tag [Code] !!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class A
{
	friend class 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!!!
Last edited on
It's wrong, because in B::operator [] you return A instead of int&. But something like that should be right:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
}

Another variant:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;
}
Last edited on
:)) its very good idea @Syuf :D i really like it . interesting !
Topic archived. No new replies allowed.