Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) operator<<

 

operator<< (pronounced as 'stream out operator') is an operator to sending data to a stream. Use operator>> to read data from a stream.

 

 

 

 

 

Example: the Hello World program

 

#include <iostream>

int main()
{
  std::cout << "Hello World" << std::endl;
}

 

 

 

 

 

Overloading operator<<

 

Prefer overloading operator<< with a free function [1]. To be able to access the private member variables, make this function a friend.

 

#include <iostream>

struct MyClass
{
  MyClass(const int value) : mValue(value) {}
  private:
  const int mValue;
  friend std::ostream& operator<<(std::ostream& os, const MyClass& myClass);
};

std::ostream& operator<<(std::ostream& os, const MyClass& myClass)
{
  os << "MyClass.value: " << myClass.mValue;
  return os;
}

int main()
{
  const MyClass myClass(13);
  std::cout << myClass << '\n';
}

 

 

 

 

 

References

 

  1. Herb Sutter. Exceptional C++. ISBN: 0-201-61562-2.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict