使用istream作为参数的命名构造函数的问题

mva*_*vaz 1 c++ stream named-constructor

我正在尝试为我的类Matrix创建一个命名构造函数,输入作为流,我可以从中读取初始化的值.

#include <istream>
// ...

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

private:
    int n;
    std::valarray< Cell > data;
};
Run Code Online (Sandbox Code Playgroud)

该方法应该或多或少地像这样实现

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;
}
Run Code Online (Sandbox Code Playgroud)

但是,在编译时,我在方法声明中得到一个错误(第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’
Run Code Online (Sandbox Code Playgroud)

但是,在使用简单参数(如int)定义和实现命名构造函数时,我无法得到这些错误.

我错过了什么?任何帮助将不胜感激.

GMa*_*ckG 6

istream在命名空间中std:

static Matrix *newFromStream(std::istream&);
Run Code Online (Sandbox Code Playgroud)

该错误表明它一旦丢失就会丢失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
}
Run Code Online (Sandbox Code Playgroud)