簡體   English   中英

使用istream作為參數的命名構造函數的問題

[英]Problem with named constructor with istream as argument

我正在嘗試為我的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)定義和實現命名構造函數時,我並沒有得到這些錯誤。

我想念什么? 任何幫助將不勝感激。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM