gpt4 book ai didi

c++ - 使用输入文件流 C++ 初始化对象的构造函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:18:54 25 4
gpt4 key购买 nike

我的“记录”构造函数如下所示:

#include "Record.h"  //both these headers #include <iostream>
#include "String.h"

Record :: Record(std::ifstream& is)
{
std :: istream & iss = static_cast<std::istream &>(is);
iss >> ID >> medium >> rating;
getline(iss, title);
if (!iss.good())
throw Record_exception(invalid_data);
}

其中 ID 是 int,medium 和 title 是用户定义的类型字符串(不是标准字符串),其中 operator>> 、getline 和 operator<< 在 istream 上定义如下

#include "String.h"

ostream& operator << (ostream& os, const String & s)
{
int str_length = s.size();
for (int i = 0; i < str_length ; i++)
os << s[i];
return os;
}

istream& operator >> (istream& is, String& str)
{
char input;
bool string_end = false;
int length = 0;
str.clear();
while (!string_end){
is.get(input);
if (!isspace(input) && is){
length++;
str +=input;
}else if (length || !is)
string_end = true;
}
return is;
}


istream& getline(std::istream& is, String& str)
{
char input;
bool string_end = false;
int length = 0;
str.clear();
while (!string_end){
is.get(input);
if (!isspace(input) && is){
length++;
str +=input;
}else if ((length && is.peek() == '\0') || !is)
string_end = true;
}
return is;
}

我将 ifstream 静态转换为一个 istream,因为我意识到编译器不接受我的“getline”和 operator<< 用于 String 和 operator<< 用于带有 ifstream 的字符串。但是我仍然不知道这是否是正确的方法

我的编译器错误现在包括:

"Record.cpp: In constructor ‘Record::Record(std::ifstream&)’: Record.cpp:26: error: invalid static_cast from type ‘std::basic_ifstream >’ to type ‘std::istream&’

我在 red_hat linux 机器上用标志“g++ -c -pedantic -Wall -fno-elide-constructors”编译

最佳答案

在您的情况下,我认为您必须了解 ifstreams 实现了 istream 接口(interface)。您的 Record 构造函数实际上不需要 ifstream。里面的所有代码只使用 istream 的公共(public)接口(interface)。所以你只需要让你的 Record 构造函数接受 istream&(而不是 ifstream&)。这也将使您的 Record 类更加通用,因为您可以将它与各种 istream 一起使用,而不仅仅是文件输入流。

但是,您的 String 类重载看起来没问题。我怀疑你试图将 static_cast fstream 转换为 istream 的方式(这是一个向上转换,永远不应该明确要求也不应该这样做),你试图解决的原始问题是你没有所有相关区域中包含的正确标题。确保在必要时包含 istream、ostream 和 fstream,而不仅仅是 iosfwd 或 iostream。如果编译器在尝试将 fstream 引用传递给需要 istream& 的函数时出错,那肯定是有问题的,最可能的解释是前向声明和缺少包含。

关于c++ - 使用输入文件流 C++ 初始化对象的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154239/

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