【问题标题】:A constructor that initializes an object using the input filestream C++使用输入文件流 C++ 初始化对象的构造函数
【发布时间】:2012-02-27 13:57:07
【问题描述】:

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

#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

#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

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

“Record.cpp:在构造函数‘Record::Record(std::ifstream&)’中: Record.cpp:26:错误:类型无效的 static_cast 'std::basic_ifstream >' 输入 ‘std::istream&’

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

【问题讨论】:

  • 你的构造函数应该只接受istream&amp;
  • 我们需要构造函数调用。此外,所有这些样板代码真的有必要吗? sscce.org
  • @KerrekSB,是的,如果我写了接口,我会这样做,但我没有,并且对应的构造函数声明不能​​更改。我只需要定义函数。
  • @sscce.org-Xeo ,我什至没有在任何主要的地方调用过构造函数。我不能用 -c 编译它,我和我的教授讨论了这两个函数的冗长性质,但同样,我们的导师要求两个具体任务并遵守他的指导方针,如果请专注于手头的问题而不是风格
  • @Leila:嗯,sscce.org 是一个链接。另外,我相当确定 operator&lt;&lt;operator&gt;&gt;getline 在此处不需要来显示您的错误。这与“风格”无关。你甚至从未在这些函数中提及 Record

标签: c++ constructor inputstream filestream


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多