所以,我在这个头文件中遇到了流插入运算符重载的问题。如果我按原样使用代码,我会在标题中收到错误消息。但是当我将声明放在主文件中时,它工作正常。
理性.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
其他两个文件,1.c 和 Rational.c(如果需要):
#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;
}