C++ifstream来构建对象

C++ ifstream to build objects

本文关键字:对象 构建 C++ifstream      更新时间:2023-10-16

对于一项作业,我被要求从两个独立的.dat文件中读入。我一直在使用ifstreams来实现这一点,但在尝试构建时,我收到以下错误消息:/usr/include/c++/4.8/bits/ios_base.h:786:5: error: ‘std::ios_base::ios_base(const std::ios_base&)’ is private。我已经设法追踪到了这条违规线路:NMEAobject fred = get_nmea_object(in_stream1);

这是我的头文件

#ifndef NMEAINPUT_H
#define NMEAINPUT_H

class NMEAinput {
public:
NMEAinput(std::string fn1, std::string fn2);
private:
std::ifstream in_stream1;
std::ifstream in_stream2;
std::ofstream out_stream;
bool test_gsv(std::string in_gsv);
NMEAobject get_nmea_object(std::ifstream in);
NMEAobject read_rmc(std::string in_rmc);
std::string* split(std::string in_string,char split_point);
};
#endif  

这是我的cpp文件:

#include <stdlib.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <list>
#include "NMEAobject.h"
#include "NMEAinput.h"
#include "GPXoutput.h"
NMEAinput::NMEAinput(std::string fn1, std::string fn2) {
in_stream1.open(fn1.c_str());
in_stream2.open(fn2.c_str());
out_stream.open("outfile.gpx");
if(!in_stream1||!in_stream2) {
    std::cout << "Error with data read";
}
std::list<NMEAobject> stream1;
std::list<NMEAobject> stream2;
NMEAobject fred = get_nmea_object(in_stream1);
stream1.push_back(fred);
stream2.push_back(get_nmea_object(in_stream2));
int stream_time = stream1.front().get_time();
stream1.pop_front();
stream1.push_back(get_nmea_object(in_stream1));
stream2.push_back(get_nmea_object(in_stream2));
GPXoutput out(out_stream);
while(!stream1.empty() && !stream2.empty()){
    if(stream1.front().get_time() - stream_time < 1){
        out.put(stream1.front().convert(),out_stream);
    }
    else{
        out.put(stream2.front().convert(),out_stream);
    }
    stream_time = stream1.front().get_time();
    stream1.pop_front();
    stream2.pop_front();
    stream1.push_back(get_nmea_object(in_stream1));
    stream2.push_back(get_nmea_object(in_stream2));*/
   // if(stream1.front() == std::NULL || stream2.front() == std::NULL) break;
}
}

NMEAobject NMEAinput::get_nmea_object(std::ifstream in_stream){
std::string line;
bool good_rmc = false;
bool good_gsv = true;
while(std::getline(in_stream,line)&&!good_rmc){
    std::string data_check = line.substr(0,3);
    if(data_check == "$GP"){
        data_check = line.substr(3,3);
        if(data_check == "GSV"){
            good_gsv = test_gsv(line);
        }
        else if (data_check =="RMC"&&good_gsv){
            NMEAobject out = read_rmc(line);
            good_rmc = true;
            return out;
        }
    } 
}
 }

iostream不可复制,但您通过值传递它们:

NMEAobject get_nmea_object(std::ifstream in);  // Wrong

应替换为:

NMEAobject get_nmea_object(std::ifstream& in);

以上内容现在通过引用,因此不会产生副本。

基本上,你的问题可以归结为这样做(试着编译这个小程序(。你会看到基本上与现在相同的错误。

#include <fstream>
using namespace std;
int main()
{
    ifstream ifs1;
    ifstream ifs2;
    ifs1 = ifs2;
}