有理类的头文件:没有类型错误

时间:2015-09-23 23:01:19

标签: c++ class types header

我已经建立了一个理性的类,这是我的.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 |错误:ISO C ++禁止声明&#39; RATION&#39;   没有类型[-fpermissive] |

     

include \ Rational.h | 41 |错误:&#39; istream&#39;没有命名类型|

     

include \ Rational.h | 42 |错误:&#39; ostream&#39;没有命名类型|

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

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

如果我需要完整的cpp实现文件或main来解决这个问题,请告诉我。另外,我使用的是codeblocks,我在构建选项中添加了include到我的编译器中。

2 个答案:

答案 0 :(得分:0)

构造函数与类具有相同的名称,并且没有返回类型。

您的函数Rations拼写不同,要么返回类型为void(不返回值),要么返回值。

答案 1 :(得分:0)

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

Rational::Rational(int n)

如果不是拼写错误,那么我不知道您为何将Rational更改为Rations

对于istreamostream,您的班级会引用它们,但您尚未宣布它们 - 编译器不知道您在谈论什么。您必须在头文件中包含正确的标题(上面类定义):

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

或者,如果您对此非常严格,请在类定义之上使用前向声明:

class istream;
class ostream;

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

相关问题