大家好,我正在尝试重载 ifstream 和 ofstream,但没有成功。
头文件:
#include <iostream>
#include <fstream>
using namespace std;
class Complex
{
private:
double real;
double imaginary;
public:
//constructors
Complex();
Complex(double newreal, double newimaginary);
~Complex();
//setter
void setReal(double newreal);
void setImaginary(double newimaginary);
//getter
double getReal();
double getImaginary();
//print
void print();
//methods
Complex conjugate();
Complex add(Complex c2);
Complex subtraction(Complex c2);
Complex division(Complex c2);
Complex multiplication(Complex c2);
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1;
return in;
}
};
测试文件:
#include <iostream>
#include <fstream>
#include <string>
#include "Complex2.h"
using namespace std;
int main()
{
Complex c1;
ifstream infile;
infile.open("in1.txt");
cout << "Reading from the file" << endl;
infile >> c1;
// write the data at the screen.
infile.close();
return 0;
}
我认为 cpp 文件并不重要,因为头文件包含 ifstream。
每次我运行这个程序我都会得到这个错误:
Reading from the file
Segmentation fault (core dumped)
我不知道怎么解决。
非常感谢。
最佳答案
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1; // This is calling this function infinitely!!
return in;
}
上面的代码为 Complex
类型实现了 operator>>
。但是,它是一个没有停止条件的递归函数。
您可能应该执行与以下类似的操作。 显然,我不知道这个类是如何编码的,所以这只是为了说明。
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
double real;
in >> real;
c1.setReal(real);
double imaginary;
in >> imaginary;
c1.setImaginary(imaginary);
return in;
}
我忽略了它是一个友元函数,所以它也可以工作。
friend ifstream& operator >> (ifstream& in, Complex &c1)
{
in >> c1.real;
in >> c1.imaginary;
return in;
}
关于C++ ifstream 和 ofstream 重载运算符从文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38232496/