【问题标题】:Using Files with headers使用带有标题的文件
【发布时间】:2018-03-30 03:22:57
【问题描述】:

尝试在头文件中使用 ifstream 时,我不断收到错误消息。他们说:

FloatList.h:14:15: error: 'ifstream' has not been declared
void getList(ifstream&);
FloatList.cpp:16:6: error: prototype for 'void FloatList::getList(std::ifstream&)'
FloatList.h:14:7: error: candidate is: void FloatList::getList(int&)
void getList(ifstream&);

这是 my.h 文件中的问题部分:

public:
    FloatList();                // constructor that sets length to 0.
    ~FloatList();               // destructor
    void getList(ifstream&);    // Member function that gets data from a file 
    void printList() const;     // Member function that prints data from that
                            // file to the screen.

};
#endif

这是我的成员函数的实现文件:

#include "FloatList.h"
#include <iostream>
#include <fstream>
using namespace std;

// Fill in the entire code for the getList function
// The getList function reads the data values from a data file
// into the values array of the class FloatList
void FloatList::getList(ifstream& file)
{
    for(int i = 0; i < MAX_LENGTH; i++)
    {
        if(file >> values[i])
            length++;
    }
}

这和我在头文件中使用 ifstream 的方式有关系吗?

【问题讨论】:

  • 你的头文件有#includes吗?
  • 不,但我在头文件中使用了 std::ifstream ,现在一切正常,谢谢。

标签: c++ file class c++11


【解决方案1】:

由于您在 .cpp 文件中声明了 using namespace stdonly,因此您有义务在头文件中为 ifstream 名称添加前缀 std::

【讨论】:

    【解决方案2】:

    您不能安全地从 std 前向声明模板,因此您自己的选择是在声明类之前包含标头。方法的原型要求: 预处理器完成包含后的代码顺序应该是这样的:

    #include <iostream>
    #include <fstream>
    class FloatList
    {
    public:
        FloatList();                // constructor that sets length to 0.
        ~FloatList();               // destructor
        void getList(std::ifstream&);    // Member function that gets data from a file 
        void printList() const;     // Member function that prints data from that
                                // file to the screen.
    
    };
    
    void FloatList::getList(std::ifstream& file)
    {
        for(int i = 0; i < MAX_LENGTH; i++)
        {
            if(file >> values[i])
                length++;
        }
    }
    

    您可以在 .cpp 文件中重新排序标题:

    #include <iostream>
    #include <fstream>
    #include "FloatList.h"
    

    因此,使用 FloatList.h 将需要这些标头。您的另一个选择是将包含指令移动到您的标题中。

    【讨论】:

      猜你喜欢
      • 2021-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多