不稳定的声明行为:Rational.h:25:错误:在'&'标记之前的预期构造函数,析构函数或类型转换

时间:2012-05-05 06:32:33

标签: c++

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

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;
}

1 个答案:

答案 0 :(得分:2)

您需要在iostream

中加入Rational.h

<强> // Rational.h

#include <iostream>

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

但是,Rational.h不包含iostream,因此编译器不知道类型ostream,因此错误。