gpt4 book ai didi

c++ - 不稳定的声明行为 : Rational. h :25: error: expected constructor, 析构函数,或 ‘&’ token 之前的类型转换

转载 作者:行者123 更新时间:2023-11-28 03:37:24 25 4
gpt4 key购买 nike

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

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

最佳答案

您需要在您的Rational.h 中包含iostream

//Rational.h

#include <iostream>

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

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

关于c++ - 不稳定的声明行为 : Rational. h :25: error: expected constructor, 析构函数,或 ‘&’ token 之前的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com