Ok our teacher gave us a .h and .cpp file for a class called "JarType" and our assignment is to overload some of the math operators. Now I know how to overload operators if I'm adding two JarTypes together. What I'm having a problem with is overloading when I have something like 5 + JarType. I know to overload something like that I need to use a friend function, but I'm having trouble figuring out exactly how to define it(this text book is terrible). I was hoping someone here could tell me how to define the overload the + operator in this class so that something like 5 + JarType can be done. Below are the .h and .cpp files

JarType.h

#pragma once

class JarType {
  public:
    // CONSTRUCTORS
    JarType ();
    // POST: #units in jar is 0

    JarType (int n);
    // POST: #units in jar is n

  //MODIFICATION member functions
    void Add(int n);
    // PRE:  n>= 0
    // POST: n units have been added to jar

  // CONSTANT member function allow you to view data without modification
    int Quantity () const;
  // PRE:  n>= 0
  // POST: returns number of units assigned to instance of JarType

  bool operator == ( JarType otherjar) const;

  private:
     int  numUnits;
  };

JarType.cpp

// Implementation file jar.cpp
// This module exports a JarType ADT
//============================================

#include "JarType.h"

// Private members of class:  int numUnits
// CONSTRUCTORS
    JarType:: JarType ()    // default constructor
    // POST: #units in jar is 0
   {  numUnits = 0;
    }

     JarType:: JarType (int n)
    // PRE: n >= 0
    // POST: #units in jar is 0
   {  numUnits = n;
   }

    void JarType::  Add ( int n)
    // PRE:  n >= 0
    // POST: n units have been added to jar
    { numUnits += n;
    }

    int JarType::Quantity () const
  // PRE: n>= 0
  // POST: returns number of units assigned to instance of JarType
    {  return numUnits;
    }

  bool JarType ::operator == ( JarType otherjar) const
     {
		  int num = otherjar.numUnits;
          return ( numUnits == num);
     }
class JarType 
{
public:
    friend JarType operator+(const JarType&,const int);

  private:
     int  numUnits;
};

JarType operator+(const JarType& right,const int add)
{
    return JarType( right.numUnits + add);
}

You should change the way you comment and the way you name your member functions. For example do not leave a space between the double semilcolon and the member functions.

JarType:: JarType
JarType::JarType

Maybe having a look at this would help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.