I have a header file and a .cpp file. I am trying to implement a prefix and postfix operator overload but I keep getting this error when setting up the overload.
fraction.h
#ifndef FRACTION_H
#define FRACTION_H
#include <iostream>
using namespace std;
class Fraction
{
public:
Fraction();
Fraction(int, int);
int getTop() {return m_top;}
int getBottom() {return m_bottom;}
void set(int t, int b) {m_top=t; m_bottom=b; reduce();
}
protected:
private:
void reduce();
int gcf(int, int);
int m_top;
int m_bottom;
};
Fraction& operator ++ (Fraction);
Fraction operator++(Fraction, int);
#endif
Main.cpp
#include <iostream>
using namespace std;
#include "fraction.h"
int main {
cout << "The fraction is" << f;
cout << "The output of ++f is " << (++f) << endl;
cout << "The fraction is" << f;
cout << "The output of f++ is " << (f++) << endl;
cout << "The fraction is" << f;
return 0;
}
Fraction& Fraction::operator ++ (Fraction){
// Increment prefix
m_top += m_bottom;
return *this;
}
Fraction Fraction::operator ++ (Fraction, int){
//Increment postfix
}
These are the two errors I get:
prefix error: "Parameter of overloaded post-increment operator must have type 'int' (not 'Fraction')"
postfix error: "Overloaded 'Operator++' must be a unary or binary operator (has 3 parameters)"
Is the prefix error actually an error with my ide? I know it must be 'int' for post-increment, but I am trying to do a pre-increment. I use xcode.
You declared the operators outside the class as non-class functions
Fraction& operator ++ (Fraction);
Fraction operator++(Fraction, int);
however then you are trying to define them like class member functions
Fraction& Fraction::operator ++ (Fraction){
// Increment prefix
m_top += m_bottom;
return *this;
}
Fraction Fraction::operator ++ (Fraction, int){
//Increment postfix
}
Either declare them as class member functions the following way
class Fraction
{
public:
Fraction & operator ++();
Fraction operator ++( int );
//...
And in this case the definition for example of the preincrement operator can look like
Fraction & Fraction::operator ++(){
// Increment prefix
m_top += m_bottom;
return *this;
}
Or declare them as non-class function that are friends of the class because they need to have access to private data members of the class
class Fraction
{
public:
friend Fraction & operator ++( Fraction & );
friend Fraction operator ++( Fraction &, int );
//...
And in this case the definition for example of the preincrement operator can look like
Fraction & operator ++( Fraction &f ){
// Increment prefix
f.m_top += f.m_bottom;
return f;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With