所以,我在这个头文件中遇到了重载流插入操作符的问题。如果我按原样使用代码,我会在标题中收到错误消息。但是当我把声明放在主文件中时,它运行正常。
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
其他两个文件,如果需要,可以使用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;
}
答案 0 :(得分:2)
您需要在iostream
Rational.h
<强> // Rational.h 强>
#include <iostream>
当您将重载声明放在1.c
中时,iostream
之前包含Rational.h
,因此编译器知道类型ostream
并且没有错误。
但是,Rational.h
不包含iostream
,因此编译器不知道类型ostream
,因此错误。