Make the inserter into a friend function : Friend « Class « C++






Make the inserter into a friend function

Make the inserter into a friend function
  

#include <iostream>
#include <cstring>
using namespace std;
class PhoneNumber {
  char name[80];
  int areaCode;
  int prefix;
  int num;
public:
  PhoneNumber(char *n, int a, int p, int nm)
  {
    strcpy(name, n);
    areaCode = a;
    prefix = p;
    num = nm;
  }
  friend ostream &operator<<(ostream &stream, PhoneNumber o);
};
// Display name and phone number.
ostream &operator<<(ostream &stream, PhoneNumber o)
{
  stream << o.name << " ";
  stream << "(" << o.areaCode << ") ";
  stream << o.prefix << "-" << o.num << "\n";
  return stream; // must return stream
}
int main()
{
  PhoneNumber a("T", 111, 555, 1234);
  PhoneNumber b("A", 312, 555, 5768);
  PhoneNumber c("T", 212, 555, 9991);
  cout << a << b << c;
  return 0;
}


           
         
    
  








Related examples in the same category

1.Friend function DemoFriend function Demo
2.Define friend function for <<Define friend function for <<
3.friend class for each other
4.Friends can access private members of a class.
5.Use friend function to access the non-public member variable