繁体   English   中英

C ++ ifstream和ofstream重载运算符从文件中读取

[英]C++ ifstream and ofstream overloading operator reading from file

大家好,我正在尝试重载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;
}

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


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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM