rational class 的头文件:无类型错误

header file for rational class : no type error

我已经构建了一个有理数 class,这是我的 .h 文件:

    #ifndef RATIONAL_H
#define RATIONAL_H
#include <iostream>

using std::istream;
using std::ostream;

class Rational
{
    public:
        Rational();
        Rational(int n);
        Rational(int n, int d); 
        Rational(const Rational& other); 

        ~Rational();

        Rational operator+(const Rational& other);
        Rational operator-(const Rational& other);
        Rational operator*(const Rational& other);
        Rational operator/(const Rational& other);

        Rational operator+(int n);
        Rational operator-(int n);
        Rational operator*(int n);
        Rational operator/(int n);

        Rational& operator=(const Rational& other);

        bool operator==(const Rational& other);
        bool operator!=(const Rational& other);
        bool operator>=(const Rational& other);
        bool operator<=(const Rational& other);
        bool operator<(const Rational& other);
        bool operator>(const Rational& other);

        bool operator==(int n);
        bool operator!=(int n);
        bool operator>=(int n);
        bool operator<=(int n);
        bool operator<(int n);
        bool operator>(int n);


        friend istream& operator>>(istream& is, Rational &r);
        friend ostream& operator<<(ostream& is, Rational &r);

    private:
        int
            num,
            den;
};

#endif // RATIONAL_H

我收到多个错误,主要是:

include\Rational.h|8|error: ISO C++ forbids declaration of 'Rations' with no type [-fpermissive]|

include\Rational.h|41|error: 'istream' does not name a type|

include\Rational.h|42|error: 'ostream' does not name a type|

和我的主文件中的其余部分(都是因为我尝试使用 >> 和 <<)。我现在已经搜索了几个小时,发现了类似的问题,尝试了多种解决方案我不想在黑暗中拍摄,我想知道问题是什么以及为什么。这里记录的是我在我的实现文件中的口粮:

Rational::Rations(int n)
{
    num = n;
    den = 1;
}

让我知道是否需要我的完整 cpp 实现文件或 main 来解决这个问题。另外,我正在使用代码块,我已经在构建选项中将 include 添加到我的编译器中。

构造函数与 class 同名并且没有 return 类型。

您的函数 Rations 拼写不同,要么需要 return 类型的 void(不是 return 值),要么需要 return一个值。

您似乎打算 Rations(int) 应该是您 class 的构造函数,但是构造函数的名称必须与 class 的名称相同:

Rational::Rational(int n)

如果不是打字错误,我不知道你为什么把 Rational 改成了 Rations

至于istreamostream,你的class引用了它们,但你没有声明它们——编译器不知道你在说什么。您必须在头文件中包含正确的头文件( class 定义之上):

#include <istream>
using std::istream;
using std::ostream;

或者,如果您要严格遵守,请在 class 定义上方使用前向声明:

class istream;
class ostream;

然后将 #include 指令放在源代码中,函数定义之上。