C ++ ifstream和ofstream重载操作符从文件读取

时间:2016-07-06 19:43:59

标签: c++ overloading operator-keyword

嘿伙计们,我试图超载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)

我不知道如何解决它。

非常感谢。

2 个答案:

答案 0 :(得分:6)

friend ifstream& operator >> (ifstream& in, Complex &c1)
{
    in >> c1; // This is calling this function infinitely!!

    return in;
}

上面的代码实现了operator>>类型的Complex。但是,它是一个没有停止条件的递归函数。

你可能应该做类似以下的事情。 显然,我不知道这个类是如何编码的,所以这只是为了说明。

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;
}

答案 1 :(得分:1)

正如我的评论中提到的,在另一个答案中,operator>>()重载只是递归调用。

解决此问题的最常见方法之一是在put()类中声明Complex函数,如:

 class Complex {
 public:
     // ...
 private:
     double real;
     double imaginary;
     istream& put(std::istream& is) {
         is >> real;
         is >> imaginary;
         return is;
     }
 };

让全局重载调用该函数:

friend ifstream& operator >> (ifstream& in, Complex &c1) {
    return c1.put(in);
}