【问题标题】:Problem with named constructor with istream as argument使用 istream 作为参数的命名构造函数的问题
【发布时间】:2010-02-07 21:48:15
【问题描述】:

我正在尝试为我的类 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)定义和实现命名构造函数时,我不会遇到这些错误。

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

【问题讨论】:

  • 你错过了std::吗?

标签: c++ stream named-constructor


【解决方案1】:

istream 在命名空间std

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

该错误表明它一旦到达istream 就会丢失。当然,在标题和源中更改它。几个注意事项:

在您的标头中,使用&lt;iosfwd&gt; 而不是&lt;istream&gt;,并在您的源文件中使用&lt;istream&gt;。这更“正确”,可能会加快编译速度。

另外,你真的要返回新分配的内存吗?这是有风险的,而且不是很安全。堆栈分配会更容易,甚至更快。

最后,请记住一点:您非常接近拥有一个好的operator&lt;&lt;。您可以根据您当前的功能实现它:

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

    pResult = Matrix::from_stream(pStream);

    // ... more book keeping
}

【讨论】:

  • 在实现中同样使用std::istream
  • @quamrana:通常假设我认为,但我会补充。
  • 谢谢,就是这样!是的,>> 运算符可能更合适。关于内存,当我从流中读取第一行时,我只知道 Matrix 的大小。你的意思是我应该做类似 Matrix m();辛 >> 米;并且我在“from_stream”中有某种调整大小的方法?
  • @mvaz:我的意思是让返回值Matrix 而不是Matrix*,并将while ( iss &gt;&gt; k) n++; Matrix *m = new Matrix( n ); 更改为while ( iss &gt;&gt; k) n++; Matrix m( n );
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
相关资源
最近更新 更多