Reputation: 1087
In this way
#include <sstream>
void f(void)
{
std::stringstream ss;
ss << "hello";
}
Everything went fine. But in this way, with an extra brackets
#include <sstream>
void f(void)
{
std::stringstream ss();
ss << "hello";
}
I got a compiler error:
[Error] invalid operands of types 'std::stringstream() {aka std::basic_stringstream<char>()}' and 'char' to binary 'operator<<'
How is that?
Upvotes: 0
Views: 62
Reputation: 3676
This is an old problem in C++.
stringstream ss();
could be interpreted in two ways. As a declaration of an object ss
of type stringstream
using the default constructor, or of a function ss
returning stringstream
and taking no parameters.
The compiler chooses the function declaration, which here (and, in my experience, usuaully) is not what the programmer intended.
Solutions are either to miss off the brackets for default construction:
stringstream ss;
Or use the C++ curly brace initialization:
stringstream ss{};
Upvotes: 3