C++ friend function for Integer class

Description

C++ friend function for Integer class

 
#include <iostream>
 
class Integer//from  www  .ja  va  2s  . co m
{
private:
  int n;
 
public:
  Integer(int m = 0);
  Integer(Integer& obj);                                          // Copy constructor
  friend  int compare(const Integer& obj1, const Integer& obj2);  // friend compare function
  int getValue() {return n;}
  void setValue(int m){ n = m; }
  void show();
};
 
// Copy constructor
Integer::Integer(Integer& obj) : n(obj.n)
{
  std::cout << "Object created by copy constructor." << std::endl;
}
 
// Constructor
Integer::Integer(int m) : n(m)
{
  std::cout << "Object created." << std::endl;
}
 
void Integer::show()
{
  std::cout << "Value is " << n << std::endl;
}
 
int compare(const Integer& obj1, const Integer& obj2)
{
  if(obj1.n < obj2.n)
    return -1;
  else if(obj1.n==obj2.n)
    return 0;
  return 1;
}
 
 
int main()
{
  std::cout << "Create i with the value 10." << std::endl;
  Integer i {10};
  i.show();
  std::cout << "Change value  of i to 15." << std::endl;
  i.setValue(15);
  i.show();
 
  std::cout << "Create j from object i." << std::endl;
  Integer j {i};
  j.show();
  std::cout << "Set value of j to 150 times that of i." << std::endl;
  j.setValue(150*i.getValue());
  j.show();
 
  std::cout << "Create k with the value 300." << std::endl;
  Integer k {300};
  k.show();
  std::cout << "Set value of k to sum of i and j values." << std::endl;
  k.setValue(i.getValue()+j.getValue());
  k.show();
 
  std::cout << "Result of comparing i and j is " << compare(i, j) << std::endl;
  std::cout << "Result of comparing k and j is " << compare(k, j) << std::endl;
}



PreviousNext

Related