1

初期化の値を読み取ることができるストリームとしての入力を使用して、クラス Matrix の名前付きコンストラクターを作成しようとしています。

#include <istream>
// ...

class Matrix
{
public:
    Matrix(int);
    // some methods
    static Matrix *newFromStream(istream&);

private:
    int n;
    std::valarray< Cell > data;
};

メソッドは多かれ少なかれこのように実装する必要があります

Matrix *Matrix::newFromStream(istream &ist) {

    // read first line and determine how many numbers there are
    string s;
    getline( ist, s );
    ...
    istringstream iss( s, istringstream::in);

    int n = 0, k = 0;
    while ( iss >> k)
        n++;
    Matrix *m = new Matrix( n );    

    // read some more values from ist and initialize        

    return m;
}

しかし、コンパイル中にメソッドの宣言でエラーが発生します (74 行目でプロトタイプが定義され、107 行目で実装が開始されます)。

hitori.h:74: error: expected ‘;’ before ‘(’ token
hitori.cpp:107: error: no ‘Matrix* Matrix::newFromStream(std::istream&)’ member function declared in class ‘Matrix’

ただし、これらのエラーは、int などの単純なパラメーターを使用して名前付きコンストラクターを定義および実装する場合には発生しません。

私は何が欠けていますか?どんな助けでも大歓迎です。

4

1 に答える 1

6

istream名前空間にありますstd:

static Matrix *newFromStream(std::istream&);

このエラーは、 に到達すると失われたことを示していますistream。もちろん、ヘッダーとソースの両方で変更してください。いくつかのメモ:

ヘッダーでは<iosfwd>の代わりに を使用<istream>し、ソース ファイルでは を使用します<istream>。これはより「正しく」、コンパイルを高速化する可能性があります。

また、新しく割り当てられたメモリを本当に返しますか? これはリスクが高く、安全とは言えません。スタック割り当てははるかに簡単で、おそらくさらに高速です。

最後に、心に留めておいていただきたいことがありますoperator<<。現在の関数の観点から実装できます。

std::istream& operator<<(std::istream& pStream, Matrix& pResult)
{
    // ... book keeping for istream

    pResult = Matrix::from_stream(pStream);

    // ... more book keeping
}
于 2010-02-07T21:52:57.440 に答える