有关重载用于读取文本文件的输入运算符>>的问题

Problems regarding Overloading the input operator >> for reading text file

本文关键字:gt 输入 问题 运算符 文件 重载 用于 读取 取文本      更新时间:2023-10-16

我有一个Point2D类,我正在尝试重载输入运算符>>

class Point2D
{
 public:
           Point2D(int,int);
           int getX();
           int getY();
           void setX(int);
           void setY(int);
           double getScalarValue();
          bool operator < ( const Point2D& x2) const
          {
            return x < x2.x;
          }
              friend istream& operator >> (istream&,Point2D);

 protected:
             int x;
             int y;
             double distFrOrigin;
             void setDistFrOrigin();

};

在我的主要功能之外

    #include <iostream>
    #include <fstream>
    #include "Line2D.h"
    #include "MyTemplates.h"
    #include <string>
    #include <set>
    using namespace std;
    istream operator >> (istream& is , Point2D p2d)
    {
        string p;
        getline(is,p,'n');
       int position = p.find(", ");
        string k = p.substr(0,position);
       if ( k == "Point2D")
       {
         string x = p.substr(10,1);
         int x_coordinate = atoi(x.c_str()); // atoi(x.c_str()) convert string x to int
         p2d.setX(x_coordinate);
       }
       return is;
    }

在我的 int main() 中

    int main()
{
   fstream afile;
   string p;
   afile.open("Messy.txt",ios::in);
   if (!afile)
   {
     cout<<"File could not be opened for reading";
     exit(-1);
   }
   Point2D abc;
   afile>>abc;
   set<Point2D> P2D;
   P2D.insert(abc);
   set<Point2D>::iterator p2 = P2D.begin();
   while ( p2 != P2D.end() )
   { 
     cout<<p2->getX();
     p2++;
   }
}

我不明白为什么我会收到错误:

C++ 禁止声明没有类型的 ISTREAM

我已经使用命名空间std包含了iostream,fstream,我不知道出了什么问题

您的代码中有几个问题。

  1. 这是出现错误消息的原因。你不会#include <iostream> Point2D.h/Line2D.h.

    正如其他人已经建议的那样,使用std::istream而不仅仅是istream

  2. 正确的operator>>()应该是

    std::istream &operator>>(std::istream &is, Point2D &p2d);
    

    请注意std::istream&Point2D&Point2D&很重要,因为否则您修改本地副本并且给定的参数保持不变。

  3. 您的输入运算符很脆弱。它容易受到或多或少的空格的影响。您还允许 x_coordinate 的正好一位数字。此外,您跳过一个字符超出Point2D, .更好的方法是只用空格分隔部分,让 iostream 库处理解析。例如

    Point2D 15 28
    

    可以由

    string tag;
    is >> tag;
    if (tag == "Point2D")
        is >> p2d.x >> p2d.y;
    return is,
    
弹出

的东西(正如 Dietmar Kühl 提到的)是你没有返回 istream 的引用。尝试更改此方法标头

istream operator >> (istream& is , Point2D p2d)

对此:

istream& operator >> (istream& is , Point2D p2d)

根据经验,返回对尚未为其创建复制构造函数的对象的引用通常是一个好主意。返回引用意味着返回对象所在的地址。要按值正确返回,需要对要返回的对象进行复制。