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

标签 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)

我不知道怎么解决。

非常感谢。

最佳答案

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/

相关文章:

c++ - 鼠标单击OpenGL无法围绕其自身中心旋转对象

c++ - 如何将RJ45称为串口进行对接?

c++ - 将 Boost 库添加到 OS X Eclipse 中的 C++ 项目

c# - 不带 out 和可选参数的方法重载

c# - 在重载方法中使用泛型

java - 对于参数类型 boolean、int ,运算符 != 和 == 未定义

c++ - 用 “code=3221225477”实现程序退出堆栈

c++ - 为什么用于字符串比较的 == 运算符相对于任一字符串长度是线性时间(看起来)?

c++ - 如何计算构造函数?

parameters - 具有可选参数的冲突重载方法