通过返回 ifstream 的运算符重载分段错误

segmentation fault by overloading operators with ifstream returning

我在 ubuntu 中用 c++ 编写了这个程序。我写了 2 个运算符重载,如下所示。但是我收到了"segmentation fault(core dumped)"。我该怎么办?

#include<iostream>
#include<fstream>
using namespace std;

class Complex{
private:
    double x;
    double y;
public:
    Complex(double a,double b){
         x=a;
         y=b;
    }

    void setx(double a){
         x=a;
    }

    void sety(double b){
         y=b;
    }

    double getx(){
         return x;
    }

    double gety(){
         return y;
    }
};
ifstream& operator>>(ifstream& file1,Complex &c){
     double d,e;
     file1>>d>>e;
     c.setx(d);
     c.sety(e);
     return file1;
}

ifstream& operator>>(ifstream& file1,char &ch){
     file1>>ch;
     return file1;
}
int  main(){
Complex c1(1,2);
Complex c2(1,2);
char ch;
ifstream file("input.data",ios::in);
file>>c1>>ch>>c2; 
return 0;
}

在 input.data 我有类似下面的内容:

1 4 + 2 3
3 1 - 4 8

该程序的目的是从文件中获取复数,其中包含运算符。

当您这样做时,您的程序将进入无限递归:

ifstream& operator>>(ifstream& file1,char &ch){
    file1>>ch;
    return file1;
}

第一行为 char 调用相同的 operator>>,所以你最终会导致堆栈溢出。

由于 operator>> 是为 std::istream 定义的,并且因为 std::ifstream 可以传递给 std::istream 上的运算符,只需删除您的实现即可解决此问题(demo).