C++ Operator Overload Global Operator Functions

Introduction

The volume() function is a public member of the Pool class, so you could implement operator<() as an ordinary function, not a member of the class. In this case the definition would be:

inline bool operator<(const Pool& pool1, const Pool& pool2)
{
  return pool1.Volume()<pool2.Volume();
}

Here's a program that uses the new comparison operator functions for Pool objects:

#include <iostream>
#include <vector>

#include <iostream>

class Pool/*from ww  w. ja  v  a2s  .c  o  m*/
{
private:
  double length {1.0};
  double width {1.0};
  double height {1.0};

public:
  // Constructors
  Pool(double lv, double wv, double hv) : length{lv}, width{wv}, height{hv} {}

  Pool() {}                                               // No-arg constructor

  Pool(const Pool& pool) :                                  // Copy constructor
      length {pool.length}, width {pool.width}, height {pool.height} {}

  double volume() const                                  // Function to calculate the volume
  { return length*width*height; }

  // Accessors
  double getLength() const { return length; }
  double getWidth() const { return width; }
  double getHeight() const { return height; }

  bool operator<(const Pool& aPool) const                  // Less-than operator
  { return volume() < aPool.volume(); }
};

// Display pool dimensions
void show(const Pool& pool)
{
  std::cout << "Pool" << pool.getLength() << "x"
            << pool.getWidth() << "x" << pool.getHeight() << std::endl;
}
inline bool operator<(const Pool& pool1, const Pool& pool2)
{
  return pool1.Volume()<pool2.Volume();
}

int main()
{
  std::vector<Pool> pools {Pool {2.0, 2.0, 3.0}, Pool {1.0, 3.0, 2.0},
    Pool {1.0, 2.0, 1.0}, Pool {2.0, 3.0, 3.0}};
  double minVol {6.0};
  std::cout << "Objects with volumes less than" << minVol << "are:\n";
  for (auto& pool : pools)
    if (pool < minVol) show(pool);

  std::cout << "Objects with volumes greater than" << minVol << "are:\n";
  for (auto& pool : pools)
    if (minVol < pool) show(pool);
}



PreviousNext

Related