【问题标题】:Error overloading >> Operator reading from file into class错误重载 >> 运算符从文件读入类
【发布时间】:2014-08-04 22:16:25
【问题描述】:

我目前正在开发一个类程序,该程序需要我重载流提取运算符 >>,以将文件中的数据直接提取到类中。我得到一个:

错误 C2678:二进制“>>”:未找到采用“std::ifstream”类型左侧操作数的运算符(或没有可接受的转换)

这是错误影响的具体代码。

int main()

#include <iostream>
#include <fstream>
#include <iomanip>
#include "stockType.h"
#include "stockListType.h"

using namespace std;

stockType myStock;
stockListType stockList;
ifstream infile;
infile.open("StockData.txt");

infile >> myStock;

stockType.h 头文件

#ifndef STOCKTYPE_H
#define STOCKTYPE_H

#include <string>
#include <fstream>
#include <iostream>


class stockType
{
public:
    stockType();
    void printStock();
    void calcPercent();



    char Symbol[3];
    float openingPrice;
    float closingPrice;
    float todayHigh;
    float todayLow;
    float prevClose;
    int volume;
    float percent;

    friend std::ifstream &operator >> (std::ifstream &in, const stockType &myStock);
};

#endif

stockType.cpp 资源文件

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include "stockType.h"

std::ifstream& operator>> (std::ifstream &in, const stockType &myStock)
{
in >> myStock.Symbol;
in >> myStock.openingPrice;
in >> myStock.closingPrice;
in >> myStock.todayHigh;
in >> myStock.todayLow;
in >> myStock.prevClose;
in >> myStock.volume;

return in;
}

我所做的大部分搜索是人们在使用 ostream 执行此操作时遇到问题,并且在程序使用期间获取他们的数据。尝试使用 ifstream 进行错误纠正并直接从 txt 文件中读取是很困难的。我可以提供任何需要的额外信息。任何帮助深表感谢。谢谢。

【问题讨论】:

  • 三思而后行!! const stockType &amp;myStock 肯定无法为该参数提供写入任何内容:P ...
  • @πάντα ῥεῖ 好点子。出于某种原因,我无法理解 const 不允许我写入它,这首先会带走 const 的意义!
  • @Deduplicator 感谢您的链接:)

标签: c++ visual-c++ operator-overloading ifstream


【解决方案1】:

您的输入操作员签名

std::ifstream& operator>> (std::ifstream &in, const stockType &myStock);
                                           // ^^^^^

没有意义。要将流中的任何内容输入到myStock 参数,它当然必须是非const。此外,您通常不希望重载 std::istream 的特定实现,因此您的签名应如下所示:

std::istream& operator>> (std::istream &in, stockType &myStock);

【讨论】:

  • 一般不应该是 std::istream& 而不是 std::ifstream& 吗?我不知道任务是不是为 ifstream 做的。
  • 是的。这个特定部分的分配状态:例如,假设 infile 是一个 ifstream 对象,并且输入文件是使用对象 infile 打开的。进一步假设 myStock 是一个股票对象。然后声明:infile >> myStock;从输入文件中读取数据并将其存储在对象 myStock 中。 (注意,该语句读取数据并将数据存储在myStock的相关组件中)
  • @user3220776 是的!你为什么不这样做呢?从我的回答中你有什么不明白的地方吗?如有必要,我愿意解释更多。
  • 哦,有道理。在查找重载概念时,我实际上已经看到了它与 const 的建议;完全不熟悉将 infile 直接重载到一个类。谢谢
  • @TimeStamp12 您可能已经看到它与输出 std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const T&amp;) 概念的解释。对于输出,const 非常有意义(参考参数不会更改)。
猜你喜欢
  • 2015-12-24
  • 1970-01-01
  • 2017-09-12
  • 2013-11-14
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多