GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 14-Feb-2006, 16:33
fevershark fevershark is offline
Junior Member
 
Join Date: Dec 2005
Posts: 32
fevershark is an unknown quantity at this point

overloading operators in a class.


i dont know much about how to over load operatorsin a class so if somebody could give me some pointers i would appreciate it.

here is my class header file
CPP / C++ / C Code:
class Fraction {
      private:
              int numerator;
              int denominator;
              int GreatestComDiv(int numer, int denom);
      public:
             Fraction();
             Fraction(int numer);
             Fraction(int numer, int denom);
             int getNumerator();
             int getDenominator();
             void store(int numer, int denom);
             void print();
};

but besides that i dont know what to do for overloading the <<, >>, <, >, <=, >=, ==, and != operators. can somebody please explain? thanks
  #2  
Old 14-Feb-2006, 18:08
davis
 
Posts: n/a

Re: overloading operators in a class.


Quote:
Originally Posted by fevershark
i dont know much about how to over load operatorsin a class so if somebody could give me some pointers i would appreciate it.

here is my class header file
CPP / C++ / C Code:
class Fraction {
      private:
              int numerator;
              int denominator;
              int GreatestComDiv(int numer, int denom);
      public:
             Fraction();
             Fraction(int numer);
             Fraction(int numer, int denom);
             int getNumerator();
             int getDenominator();
             void store(int numer, int denom);
             void print();
};

but besides that i dont know what to do for overloading the <<, >>, <, >, <=, >=, ==, and != operators. can somebody please explain? thanks

The first thing to do is to try to figure out what you want to accomplish with each operator that you implement. For example, if you create two instances of your Fraction class now and try to assign one to the other, you will receive a compiler error...remembering that assignment is "=" and equality is "==" in code.

So, for an assignment operator, what arguments do you need and what return value must you give back? Do the same for each of the operators you want to implement.

CPP / C++ / C Code:
Fraction& Fraction::operator=( const Fraction& rhs );
bool Fraction::operator==( const Fraction& rhs );
bool Fraction::operator!=( const Fraction& rhs );
...and so on.

Then decide what "test" must each of these operations "pass" in order to satisfy the needs of the return type. Will the internal representation of the instantiated fractional value be the same (equality) as another instance of the same class..or not (inequality)?

These "seem" difficult at first because the syntax is perhaps a bit confusing and, in many cases, you're not simply working with POD. However, in this particular case, you have a very simple representation that will be very easy to implement these operations. I'd take it to another level and try to decide how I might implement operators ++ and -- in both prefix and postfix forms!

Imagine a fraction 9/16ths...just for kicks. Wouldn't operator++() add another 16th to it so that the fractional representation is now 10/16ths, which would reduce to 5/8ths? And, wouldn't the decrementing operator subtract a 16th from 9/16ths so that you ended up with an internal representation of 8/16ths or 1/2?

Something to kick around.

Also, I'd recommend not getting into the habbit of selectively shortening things like: GreatestComDiv

Spell it out completely and, whenever possible, try to figure out what the "normal" term is and use it. I believe that GreatestCommonFactor is the preferred term, which could then logically be abbreviated GCF, in this context, though definitely does not necessarily need to be shortened.


:davis:
  #3  
Old 14-Feb-2006, 19:37
fevershark fevershark is offline
Junior Member
 
Join Date: Dec 2005
Posts: 32
fevershark is an unknown quantity at this point

Re: overloading operators in a class.


this is what i have to do. and i have to define <<, and >> operators for use too.

Write a main program to test your operators by using cin and >> to obtain two fractions and cout and << to display the original fractions, and then by creating a new fraction that is the sum of the first two, displaying that fraction (along with appropriate labels!), and then displaying the comparisons of the original two fractions for each of the relational operators. An example of the latter task, if you were to input the two fractions 4/5 and 12/7, would be the display of:

4/5 + 12/7?

4/5 < 12/7? true

4/5 > 12/7? false

4/5 <= 12/7? true

4/5 >= 12/7? false

4/5 == 12/7? false

4/5 != 12/7? true
  #4  
Old 15-Feb-2006, 12:42
davis
 
Posts: n/a

Re: overloading operators in a class.


Quote:
Originally Posted by fevershark
this is what i have to do. and i have to define <<, and >> operators for use too.

Write a main program to test your operators by using cin and >> to obtain two fractions and cout and << to display the original fractions, and then by creating a new fraction that is the sum of the first two, displaying that fraction (along with appropriate labels!), and then displaying the comparisons of the original two fractions for each of the relational operators. An example of the latter task, if you were to input the two fractions 4/5 and 12/7, would be the display of:

4/5 + 12/7?

4/5 < 12/7? true

4/5 > 12/7? false

4/5 <= 12/7? true

4/5 >= 12/7? false

4/5 == 12/7? false

4/5 != 12/7? true

...it sounds like you've got more than a fair idea of what is needed to be done. Is there a question in all of this somewhere? If you're having difficult in understanding what implementation is required, how about taking a look at this code for some ideas?

CPP / C++ / C Code:
#include <iostream>
#include <fstream>

using namespace std;

class Box
{
public:
    Box() : m_height( 0 ), m_length( 0 ), m_depth( 0 ), m_weight( 0 ){}
    Box( const float height, const float length, const float depth, const float weight ) :
    m_height( height ), m_length( length ), m_depth( depth ), m_weight( weight ){}
    Box( const Box& rhs )
    {
        m_height = rhs.m_height;
        m_length = rhs.m_length;
        m_depth  = rhs.m_depth;
        m_weight = rhs.m_weight;
    }
    virtual ~Box() {}
    Box& operator=( const Box& rhs )
    {
        m_height = rhs.m_height;
        m_length = rhs.m_length;
        m_depth  = rhs.m_depth;
        m_weight = rhs.m_weight;
        return *this;
    }
    bool operator==( const Box& rhs )
    {
        bool bEquality = false;
        if( this == &rhs )
        {
            bEquality = true;
        }
        if( m_height == rhs.m_height &&
            m_length == rhs.m_length &&
            m_depth  == rhs.m_depth &&
            m_weight == rhs.m_weight )
        {
            bEquality = true;
        }
        return bEquality;
    }
    bool operator!=( const Box& rhs )
    {
        return !( *this == rhs );
    }

    const float getVolume() const
    {
        return m_height * m_length * m_depth;
    }

    bool operator<( const Box& rhs )
    {
        bool bLessThan = false;
        if( getVolume() < rhs.getVolume() &&
            m_weight < rhs.m_weight )
        {
            bLessThan = true;
        }
        return bLessThan;
    }
    bool operator>( const Box& rhs )
    {
        bool bGreaterThan = false;
        if( getVolume() > rhs.getVolume() &&
            m_weight > rhs.m_weight )
        {
            bGreaterThan = true;
        }
        return bGreaterThan;
    }
    bool operator<=( const Box& rhs )
    {
        bool bLessThanEqualTo = false;
        if( getVolume() <= rhs.getVolume() &&
            m_weight <= rhs.m_weight )
        {
            bLessThanEqualTo = true;
        }
        return bLessThanEqualTo;
    }
    bool operator>=( const Box& rhs )
    {
        bool bGreaterThanEqualTo = false;
        if( getVolume() >= rhs.getVolume() &&
            m_weight >= rhs.m_weight )
        {
            bGreaterThanEqualTo = true;
        }
        return bGreaterThanEqualTo;
    }
    const float GetHeight() const
    {
        return m_height;
    };
    void SetHeight( const float height )
    {
        m_height = height;
    };
    const float GetLength() const
    {
        return m_length;
    };
    void SetLength( const float length )
    {
        m_length = length;
    };
    const float GetDepth() const
    {
        return m_depth;
    };
    void SetDepth( const float depth )
    {
        m_depth = depth;
    };
    const float GetWeight() const
    {
        return m_weight;
    };
    void SetWeight( const float weight )
    {
        m_weight = weight;
    };
    void ToStdOut()
    {
        cout << "Box = h:" << m_height << ", l:" << m_length << ", d:" << m_depth << ", w:" << m_weight << endl;
    }
    
private:
    float m_height;
    float m_length;
    float m_depth;
    float m_weight;

public:
    friend ostream& operator<<( ostream& os, const Box& box )
    {
        os << box.m_height << " " << box.m_length << " " << box.m_depth << " " << box.m_weight << endl;
        os << endl;
        return os;
    }
    friend istream& operator>>( istream& is, Box& box )
    {
        float h, l, d, w;
        is >> h >> l >> d >> w;
        box.m_height  = h;
        box.m_length  = l;
        box.m_depth   = d;
        box.m_weight  = w;
        return is;
    }
    
};

int main( int argc, char* argv[] )
{
    Box b1( 1, 2, 3, 4 ), b2;
    ofstream ofs; 
    ofs.open( "output.dat" );
    ofs << b1 << endl << "End of File";
    ofs.close();

    ifstream ifs( "output.dat" );
    ifs >> b2;
    ifs.close();
    
    b1.ToStdOut();
    b2.ToStdOut();
    b2.SetWeight( 90 );
    b2.ToStdOut();

    if( b1 == b2 )
    {
        cout << "b1 == b2" << endl;
    }
    else
    {
        cout << "b1 != b2" << endl;
    }

    Box b3( 1, 2, 3, 4 );
    if( b1 != b3 )
    {
        cout << "b1 != b3" << endl;
    }
    else
    {
        cout << "b1 == b3" << endl;
    }

    Box b4( 4, 3, 2, 1 );
    if( b3 == b4 )
    {
        cout << "b3 == b4" << endl;
    }
    else
    {
        cout << "b3 != b4" << endl;
    }

    if( b1 > b3 )
    {
        cout << "b1 > b3"  << endl;
    }
    if( b1 >= b3 )
    {
        cout << "b1 >= b3" << endl;
    }
    if( b3 < b1 )
    {
        cout << "b3 < b1" << endl;
    }
    if( b3 <= b1 )
    {
        cout << "b3 <= b1" << endl;
    }

    Box* pB1 = &b1;
    if( b1 == *pB1 )
    {
        cout << "b1 == *pB1" << endl;
    }

    // etc...
    
    return 0;
}

// output:
Box = h:1, l:2, d:3, w:4
Box = h:1, l:2, d:3, w:4
Box = h:1, l:2, d:3, w:90
b1 != b2
b1 == b3
b3 != b4
b1 >= b3
b3 <= b1
b1 == *pB1


It may give you an idea of what you want to do. Obviously, I quickly implemented a test for equality/inequality in something that doesn't really have an exact equality test...except when the two objects are the same object. Since your Fractions are going to be numerically based, it will be much easier to implement a good and representative test for equality. In my "Box" example, I could only use volume and weight as some manner of equality. We can see where the exception to a "real world" box would occur if perhaps the linear dimensions for one box were 100 x 100 x 1 versus 1 x 1 x 10000. The volume would be the same, but the transport "issues" would differ dramatically...so equality by both weight and volume alone would probably not be a real good example of true equality in this particular case. The class would need to be modified to somehow judge if the linear dimensions were outside of some idea of "reasonable proportions" in order to be worthy of a "real world" box as might be used in a shipping calculation or ship/container loading application.

In your Fraction class, you can easily support the it using the values. Becareful to ensure that you test to see if 5/10ths is equal to 1/2...etc. That is about all I can think of to suggest at the moment.

Also, you may want to ensure that your Fraction doesn't accept just:

1/2 on streamed input, output, but also:
1:2 ...it might be worth some "extra points."



:davis:
  #5  
Old 22-Feb-2006, 08:50
fevershark fevershark is offline
Junior Member
 
Join Date: Dec 2005
Posts: 32
fevershark is an unknown quantity at this point

Re: overloading operators in a class.


well guys this is what i have so far i know there is a few msitakes in my code but i dont know what to do to fix them can somebody please help. here is my files and my errorlog thanks.

Header File
CPP / C++ / C Code:
#include <iostream>
using namespace std;

#ifndef FRACTION
#define FRACTION

class Fraction {
      private:
              int numerator;
              int denominator;
              int GreatestComDiv(int numer, int denom);
      public:
             Fraction();
/*----------------------------------------------------------------------
      Construct a class object (default).

      Precondition:  None.
      Postcondition: Fraction object is initialized to 0/1;
-----------------------------------------------------------------------*/
             Fraction(int numer);
/*----------------------------------------------------------------------
      Construct a class object (one value).

      Precondition:  None.
      Postcondition: Fraction object is initialized to numer/1;
-----------------------------------------------------------------------*/
             Fraction(int numer, int denom);
/*----------------------------------------------------------------------
      Construct a class object (two values).

      Precondition:  None.
      Postcondition: Fraction object is initialized to numer/denom;
-----------------------------------------------------------------------*/
             int getNumerator();
/*----------------------------------------------------------------------
      Retrieve the value stored in the myHours data member. 

      Precondition:  None.
      Postcondition: Value stored in Numerator is returned.
-----------------------------------------------------------------------*/
             int getDenominator();
/*----------------------------------------------------------------------
      Retrieve the value stored in the myHours data member. 

      Precondition:  None.
      Postcondition: Value stored in Denominator is returned.
-----------------------------------------------------------------------*/
             void store(istream & in, Fraction & fr);
/*----------------------------------------------------------------------
      Stores the values of fractions (two values).

      Precondition:  None.
      Postcondition: Fraction object is initialized to numer/denom and
      then normalized and reduced;
-----------------------------------------------------------------------*/
             void print(ostream & out, Fraction & fr)const;
/*----------------------------------------------------------------------
     Prints the fractions dtored in there corresponding names.

     Precondition:  stored fraction
     Postcondition: The fraction is displayed on the screen. 
----------------------------------------------------------------------*/
};//Fraction
//----- << and >> operators
ostream & operator<<(ostream & out, Fraction & fr);
/*------------------------------------------------------------------------
  Overloaded ouput operator

  Precondition:  The ostream out is open.
  Postcondition: The time represented by this Fraction object has been
      inserted into ostream out (via Print()); reference to out
      is returned.
------------------------------------------------------------------------*/
istream & operator>>(istream & in, Fraction & fr);
/*------------------------------------------------------------------------
  Overloaded input operator

  Precondition:  The istream in is open; input from in has the form
      (a/b); 
  Postcondition: Values have been extracted from in (via store()) and 
      stored in this Fractions object's data members; reference to in is
      returned.
--------------------------------------------------------------------------*/
/***** Relational operators *****/
Fraction operator+(Fraction & fr1, Fraction & fr2);
/*----------------------------------------------------------------------
   Add one Fraction object to another Fraction object.

   Precondition:  None.
   Postcondition: fr3 is returned when fr1 is added to fr2  
---------------------------------------------------------------------*/
bool operator<(Fraction & fr1, Fraction & fr2);
/*----------------------------------------------------------------------
   Determine if one Fraction object is less than another Fraction object.

   Precondition:  None.
   Postcondition: true is returned if fr1 is less than frt2 and
       false otherwise.
---------------------------------------------------------------------*/
bool operator>(Fraction & fr1, Fraction & fr2);
/*----------------------------------------------------------------------
   Determine if one Fraction object is greater than another Fraction object.

   Precondition:  None.
   Postcondition: true is returned if fr1 is greater than fr2 and
       false otherwise.
----------------------------------------------------------------------*/
bool operator==(Fraction & fr1, Fraction & fr2);
/*----------------------------------------------------------------------
   Determine if one Fraction object is equal to another Fraction object.

   Precondition:  None.
   Postcondition: true is returned if fr1 is equal to fr2 and
      false otherwise.
----------------------------------------------------------------------*/

bool operator<=(Fraction & fr1, Fraction & fr2);
/*----------------------------------------------------------------------
   Determine if one Fraction object is less than or equal to 
   another Fraction object.

   Precondition:  None.
   Postcondition: true is returned if fr1 is less than or equal 
       to fr2 and false otherwise.
----------------------------------------------------------------------*/
bool operator>=(Fraction & fr1, Fraction & fr2);
/*----------------------------------------------------------------------
   Determine if one Fraction object is greater than or equal to 
   another Fraction object.

   Precondition:  None.
   Postcondition: true is returned if fr1 is greater than or equal 
       to fr2 and false otherwise.
----------------------------------------------------------------------*/
bool operator!=(Fraction & fr1, Fraction & fr2);
/*----------------------------------------------------------------------
   Determine if one Fraction object is not equal to another Fraction object.

   Precondition:  None.
   Postcondition: true is returned if fr1 is not equal to fr2 and
       false otherwise.
----------------------------------------------------------------------*/
#endif

Implementation File
CPP / C++ / C Code:
#include "Fraction.hpp"
#include <iostream>
#include <cstdlib>

/*used when no input is provided */
Fraction::Fraction()
{
     numerator = 0;
     denominator = 1;
}//Fraction::Fraction()

/*used when 1 input is provided */
Fraction::Fraction(int numer)
{
     numerator = numer;
     denominator = 1;
}//Fraction::Fraction(int numer)

/*used when both inputs are provided then simplifies and 
normalizes the fraction and then stores it*/
Fraction::Fraction(int numer, int denom)
{
     if(denom == 0)
     {
        cout << "Can not Divide By 0!  Program Terminating." << endl;
        cout << endl;
        system ("pause");
        exit(100);
     }
     if(denom < 0)
     {
        denom = -denom;
        numer = -numer;
     }
     int gcd = GreatestComDiv (abs(numer), abs(denom));
     numer = numer/gcd;
     denom = denom/gcd;
     store(numer, denom);
}//Fraction::Fraction(int numer, int denom)

/*Gets the numerator out of fractions*/
int Fraction::getNumerator()
{
    return numerator;
}//int Fraction::getNumerator()

/*Gets the denominator out of fractions*/
int Fraction::getDenominator()
{
    return denominator;
}//int Fraction::getDenominator()

/*used to storefractions that are provided then simplifies and 
normalizes the fraction*/
void Fraction::store(int numer, int denom)
{
     numerator = numer;
     denominator = denom; 
         
    if(denominator == 0)
     {
        cout << "Can not Divide By 0!  Program Terminating!!!" << endl;
        cout << endl;
        system ("pause");
        exit(100);
     }
     if(denominator < 0)
     {
        denominator = -denominator;
        numerator = -numerator;
     }
     int gcd = GreatestComDiv (abs(numer), abs(denom));
     numerator = numerator/gcd;
     denominator = denominator/gcd;
     return;
}//Fraction::store

/*prints the fraction*/
void Fraction::print(ostream & out, Fraction & fr)const
{
     out<< numerator << "/" << denominator;
     return;
}//Fraction::print

/*finds the Greatest Commom Divisor and sends it 
to store and function with 2 parameters*/
int Fraction::GreatestComDiv(int numer, int denom)
{
    if (numer < denom)
       {
              int temp = numer;
              numer = denom;
              denom = temp;
       }
    if  (denom == 0)
     return numer;
    else
      return GreatestComDiv(denom, numer % denom);
}//int Fraction::GreatestComDiv(int numer, int denom)

//----- Definition of operator<<()
ostream & operator<<(ostream & out, Fraction & fr)
{
  fr.print(out, fr);
  return out;
}
//----- Definition of operator>>()
istream & operator>>(istream & in, Fraction & fr)
{
  int a;
  int b;
  char ch;
  
  cin >> a >> ch >> b;
  fr.store(a,b);
  return in;
}
/***** Relational operators *****/
Fraction operator+(Fraction & fr1, Fraction & fr2)
{
    int a = fr1.getNumerator();
	int b = fr1.getDenominator();
	int c = fr2.getNumerator();
	int d = fr2.getDenominator();
    Fraction fr3;
    fr3.store(a*d+c*b,b*d);
    return fr3;
}
bool operator<(Fraction & fr1, Fraction & fr2)
{
  return (double) fr1.getNumerator()/fr1.getDenominator() < 
	     (double) fr2.getNumerator()/fr2.getDenominator();
}
bool operator>(Fraction & fr1, Fraction & fr2)
{
  return (double) fr1.getNumerator()/fr1.getDenominator() > 
	     (double) fr2.getNumerator()/fr2.getDenominator();
}
bool operator<=(Fraction & fr1, Fraction & fr2)
{
  return (double) fr1.getNumerator()/fr1.getDenominator() <= 
	     (double) fr2.getNumerator()/fr2.getDenominator();
}
bool operator>=(Fraction & fr1, Fraction & fr2)
{
  return (double) fr1.getNumerator()/fr1.getDenominator() >=
	     (double) fr2.getNumerator()/fr2.getDenominator();
}
bool operator==(Fraction & fr1, Fraction & fr2)
{
  return (double) fr1.getNumerator()/fr1.getDenominator() == 
         (double) fr2.getNumerator()/fr2.getDenominator();
}
bool operator!=(Fraction & fr1, Fraction & fr2)
{
  return (double) fr1.getNumerator()/fr1.getDenominator() != 
	     (double) fr2.getNumerator()/fr2.getDenominator();
}

Main Program
CPP / C++ / C Code:
#include <iostream>
#include "Fraction.hpp"

using namespace std;

int main()
{
    Fraction fr1;
    Fraction fr2;
	cout << "Please Enter Your First Fraction In This Form (a/b): ";
	cin >> fr1;
	cout << "\nPlease Enter Your Second Fraction In This Form (a/b): ";
	cin >> fr2;
	
	Fraction fr3 = fr1 + fr2;
	
	cout << "\nYour First Fraction Added To Your second Fraction Is: " << fr3 << endl;
	
	cout << fr1 << ' < ' << fr2 << ' = ' << << boolalpha << (fr1 < fr2) << endl << endl;
	cout << fr1 << ' > ' << fr2 << ' = ' << << boolalpha << (fr1 < fr2) << endl << endl;
	cout << fr1 << ' <= ' << fr2 << ' = ' << << boolalpha << (fr1 < fr2) << endl << endl;
	cout << fr1 << ' => ' << fr2 << ' = ' << << boolalpha << (fr1 < fr2) << endl << endl;
	cout << fr1 << ' == ' << fr2 << ' = ' << << boolalpha << (fr1 < fr2) << endl << endl;
	cout << fr1 << ' != ' << fr2 << ' = ' << << boolalpha << (fr1 < fr2) << endl << endl;
	
	system("pause");
    return 0;
}//main

ERRORLOG
Quote:
C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.cpp In constructor `Fraction::Fraction(int, int)':

46 C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.cpp no matching function for call to `Fraction::store(int&, int&)'

note C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.hpp:60 candidates are: void Fraction::store(std::istream&)

note C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.hpp:60 At global scope:

64 C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.cpp prototype for `void Fraction::store(int, int)' does not match any in class `Fraction'

60 C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.hpp void Fraction::store(std::istream&)

C:\Documents and Settings\Administrator\Desktop\homework\Project3\M akefile.win [Build Error] [Fraction.o] Error 1
  #6  
Old 22-Feb-2006, 09:38
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,245
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all

Re: overloading operators in a class.


Quote:
46 C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.cpp no matching function for call to `Fraction::store(int&, int&)'
You have no function called store() passing in integer references in your class.

Quote:
64 C:\Documents and Settings\Administrator\Desktop\homework\Project3\F raction.cpp prototype for `void Fraction::store(int, int)' does not match any in class `Fraction'
You have no function called store() passing in integer values in your class
__________________

Age is unimportant -- except in cheese
  #7  
Old 22-Feb-2006, 14:08
fevershark fevershark is offline
Junior Member
 
Join Date: Dec 2005
Posts: 32
fevershark is an unknown quantity at this point

Re: overloading operators in a class.


Quote:
Originally Posted by WaltP
You have no function called store() passing in integer references in your class.


You have no function called store() passing in integer values in your class


thanks for that help WALT but i am having problems with this part now.

CPP / C++ / C Code:
Fraction operator+(Fraction & fr1, Fraction & fr2);

Fraction operator+(Fraction & fr1, Fraction & fr2)
{
    int a = fr1.getNumerator();
	int b = fr1.getDenominator();
	int c = fr2.getNumerator();
	int d = fr2.getDenominator();
    Fraction sum;
    sum.store(a*d+c*b, b*d);
    return sum;
}

CPP / C++ / C Code:
store(istream & in, int & numer, int & denom)
how can i get this to work with the above segment?
  #8  
Old 22-Feb-2006, 16:35
davis
 
Posts: n/a

Re: overloading operators in a class.


Quote:
Originally Posted by fevershark
thanks for that help WALT but i am having problems with this part now.

CPP / C++ / C Code:
Fraction operator+(Fraction & fr1, Fraction & fr2);

Fraction operator+(Fraction & fr1, Fraction & fr2)
{
    int a = fr1.getNumerator();
	int b = fr1.getDenominator();
	int c = fr2.getNumerator();
	int d = fr2.getDenominator();
    Fraction sum;
    sum.store(a*d+c*b, b*d);
    return sum;
}

CPP / C++ / C Code:
store(istream & in, int & numer, int & denom)
how can i get this to work with the above segment?

Take a look at your store parameters list. You're trying to use it with only two arguments and you've declared it to take three. You either need to overload store so that it takes two int args or call it with a istream reference from your operator+ code.


:davis:
  #9  
Old 22-Feb-2006, 17:06
fevershark fevershark is offline
Junior Member
 
Join Date: Dec 2005
Posts: 32
fevershark is an unknown quantity at this point

Re: overloading operators in a class.


Quote:
Originally Posted by davis
Take a look at your store parameters list. You're trying to use it with only two arguments and you've declared it to take three. You either need to overload store so that it takes two int args or call it with a istream reference from your operator+ code.


:davis:

i have tryed put the 3 arguments in with the overloading operator+ but it says i can only pass it 1 or 2 arguments and not 3. so what do i need to do to overload the store function?
  #10  
Old 22-Feb-2006, 18:54
davis
 
Posts: n/a

Re: overloading operators in a class.


Quote:
Originally Posted by fevershark
i have tried put the 3 arguments in with the overloading operator+ but it says i can only pass it 1 or 2 arguments and not 3. so what do i need to do to overload the store function?

I dunno, maybe implement a store function that takes the two parameters that you want?

Better yet, why not an args ctor that takes the two parameters that you want?

...that would be easiest, especially since you already have one!

CPP / C++ / C Code:

Fraction(int numer, int denom); // in your header file...


Fraction operator+(Fraction & fr1, Fraction & fr2)
{
    int a = fr1.getNumerator();
    int b = fr1.getDenominator();
    int c = fr2.getNumerator();
    int d = fr2.getDenominator();
// Fraction sum;
// add this
    Fraction sum( a*d+c*b, b*d );
// sum.store(a*d+c*b, b*d);
    return sum;
}

...easier? Shouldn't you also be making a lot of parameters const in your declarations/implementations?


:davis:
 
 

Recent GIDBlogDeveloping GUIs with wxPython (Part 2) by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Introduction to .NET LuciWiz .NET Forum 5 09-Aug-2007 04:53
Error C2146: syntax error : missing ',' before identifier 'C4' mattchew008 C++ Forum 2 19-Dec-2004 06:06
Help! Some basal questions about MFC xutingnjupt MS Visual C++ / MFC Forum 1 05-Dec-2004 03:38
hashing help saiz66 C++ Forum 1 06-Jul-2004 06:16

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 18:46.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.