以 istream 作为参数的命名构造函数的问题
我正在尝试为我的类 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)定义和实现命名构造函数时获取。
我缺少什么?任何帮助将不胜感激。
I'm trying to create a named constructor for my class Matrix, with an input as a stream from which I can read the values for the initialization.
#include <istream>
// ...
class Matrix
{
public:
Matrix(int);
// some methods
static Matrix *newFromStream(istream&);
private:
int n;
std::valarray< Cell > data;
};
The method should be implemented more or less like this
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;
}
However, while compiling, I get an error in the declaration of the method (line 74 is where the prototype is defined, and 107 where the implementation starts)
hitori.h:74: error: expected ‘;’ before ‘(’ token
hitori.cpp:107: error: no ‘Matrix* Matrix::newFromStream(std::istream&)’ member function declared in class ‘Matrix’
These errors, however, I do not get when defining and implementing a named constructor with a simple parameter, like an int.
What am I missing? Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
istream
位于命名空间std
中:该错误表明一旦到达
istream
就丢失了。当然,请在标头和源代码中更改它。一些注意事项:在标头中,使用
而不是
,并在源文件中使用
>。这更“正确”,并且可能会加快编译速度。另外,你真的想返回新分配的内存吗?这是有风险的,而且不太安全。堆栈分配会容易得多,甚至可能更快。
最后,需要记住一点:您已经非常接近拥有一个优秀的
操作员<<
了。您可以根据您当前的功能来实现它:istream
is in the namespacestd
:The error indicates it's lost once it gets to
istream
. Change it in both header and source, of course. A couple notes:In your header, use
<iosfwd>
instead of<istream>
, and in your source file use<istream>
. This is more "correct" and may speed up compilation.Also, do you really want to return newly allocated memory? This is risky and isn't terribly safe. Stack-allocation would be much easier, and maybe even faster.
Lastly, just something to keep in mind: You're very close to having a good
operator<<
. You can implement it in terms of your current function: