0

所以,我在这个头文件中遇到了流插入运算符重载的问题。如果我按原样使用代码,我会在标题中收到错误消息。但是当我将声明放在主文件中时,它工作正常。

理性.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;
}
4

1 回答 1

2

你需要iostream在你的Rational.h

//Rational.h

#include <iostream>

当您将重载声明放入1.c,iostream之前包含在内Rational.h,因此编译器知道类型ostream并且没有错误。

但是,在这种情况下Rational.h不包括iostream,编译器不知道类型ostream,因此不知道错误。

于 2012-05-05T06:37:20.677 回答