2016-07-06 7 views
-2

ちょっと私はifstreamとofstreamをオーバーロードしようとしていますが、成功しません。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; 
} 

私は、ヘッダファイルはifstreamを含むためのcppファイルが重要だったと思いdidntの。私はそれを修正する方法を知らない

Reading from the file 
Segmentation fault (core dumped) 

:私はこのプログラムを実行する

毎回私はこのエラーを取得します。

ありがとうございました。

+1

'in >> c1;'はスタックが使い果たされるまで、単に演算子の関数定義を再帰的に呼び出します。 –

答えて

2
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; 
} 
+0

私は私的なデータを解析するためのカプセル化を好むでしょう。おそらく 'private'クラスメンバ関数を使って行うべきです。 –

+0

@πάνταῥεῖここに引数はありません。 –

1

私のコメントで述べたように、そして他の回答で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); 
} 
関連する問題