so, I have been having issues in this header file overloading the stream insertion operator. I receive the error message in the title if I use the code as is. But when I put the declaration in the main file, it works fine.
Rational.h
#ifndef RATIONAL_H
#define RATIONAL_H
using namespace std;
class Rational{
private:
int numerator;
unsigned int denominator;
bool isNegative;
public:
Rational();
Rational(int);
Rational(int, int);
bool operator==(const Rational&);
Rational& operator++(int); //Unused int
Rational operator-(const Rational&);
Rational operator+(const Rational&);
Rational operator*(const Rational&);
Rational operator/(const Rational&);
};
ostream& operator<<(ostream&, Rational&); //Erroneous code
#endif
The other two files, 1.c and Rational.c if needed:
#include "Rational.h"
#include <iostream>
#include <math.h>
using namespace std;
Rational::Rational(){
numerator = 0;
denominator = 1;
}
Rational::Rational(int num){
numerator = num;
denominator = 1;
}
Rational::Rational(int num, int den){
//Determine negativity
if(num < 0 xor den < 0){ //If negative
if(num > 0){
num *= -1;
}
}
numerator = num;
denominator = abs(den);
}
bool Rational::operator==(const Rational& rhs){
return (numerator/(double)denominator == rhs.numerator/(double)(rhs.denominator));
}
ostream& operator<<(ostream& os, Rational& input){
os << "Moo";
return os;
}
/*
private:
int numerator;
unsigned int denominator;
bool isNegative;
public:
Rational(int, int);
bool operator==(const Rational&);
Rational& operator++(int); //Unused int
Rational operator-(const Rational&);
Rational operator+(const Rational&);
Rational operator*(const Rational&);
Rational operator/(const Rational&);
*/
1.c
#include <iostream>
#include "Rational.h"
using namespace std;
int main(){
Rational test = Rational(2);
cout << test << endl;
}
You need to include
iostreamin yourRational.h//Rational.h
When you put the overload declaration in
1.c,iostreamis included beforeRational.hand hence compiler knows the typeostreamand there is no error.However,
Rational.hdoes not includeiostreamso in that case compiler does not know the typeostreamand hence the error.