I tried to create generic stream class holder, but it seems like I cannot pass std::cout
to it, the code:
#include <iostream>
struct x
{
std::ostream &o;
x(std::ostream &o):o(o){}
};
int main()
{
x(std::cout);
x.o<<"Hi\n";
return 0;
}
fails when compiled as:
c++ str.cc -o str -std=c++11
str.cc: In function ‘int main()’:
str.cc:11:14: error: invalid use of qualified-name ‘std::cout’
str.cc:12:4: error: expected unqualified-id before ‘.’ token
Why?
x(std::cout);
is equivalent to
x std::cout;
which tries to declare a local variable called std::cout
. That's not allowed.
If you wanted to declare a variable of type x
, passing std::cout
to its constructor, then that's
x x(std::cout);
although, for the sake of your sanity, it might be better to give it a different name to the class (and change the following line to use that name).
Use:
int main()
{
x object(std::cout);
object.o << "Hi\n";
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.