C++ Operator[]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct ptr {

int operator[](int a){
   return 3;
}

};

int main() {

   ptr x;
   cout << x[1];
	
}


I like this "operator thing", but how can do the same without the brackets? E.g. "cout << x" instead of "cout << x[n]" and get the same output.
Last edited on
Tell the compiler what to do when it sees
standard_output_stream << your_class
By overloading operator<< for the involved types:
std::ostream& operator<<(std::ostream& os, ptr p) { return os << 3; }
Thanks mbozzi, it works great outside the struct. Is it possible to have it inside the struct somehow so I can access a member that way?
Last edited on
No: if it was a member function, it would need to be a member of std::ostream. This isn't possible.

However, you can make it a friend of your own class:

1
2
3
4
5
struct ptr 
{ 
  friend std::ostream& operator<<(std::ostream& os, ptr)
  { return os << 3; }
};

Friend functions are not member functions, but they have access to the protected and private members of the classes they're friends with.
Last edited on
Struct member access ...
1
2
3
4
5
6
7
8
9
struct ptr 
{
  int val {3}; // public by default
};

std::ostream& operator<< (std::ostream& os, const ptr& rhs )
{
  return os << rhs.val;
}

Rather than friend, the op<< could be just syntactic sugar for a member:
1
2
3
4
5
6
7
8
9
10
11
12
13
struct ptr 
{
  std::ostream& print( std::ostream& os ) const {
    return os << val;
  }
private:
  int val {3};
};

std::ostream& operator<< ( std::ostream& os, const ptr& rhs )
{
  return rhs.print( os );
}


Perfect! Thank you both.
Topic archived. No new replies allowed.