C++ 二进制表达式的无效操作数('ostream'(又名'basic_ostream<char>')和'ostream')
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20029164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ostream')
提问by JASON
I'm trying to do
我正在尝试做
cout << Print(cout);
However, there is an "invalid operands to binary expression ('ostream' (aka 'basic_ostream') and 'ostream')" error when compiling.
cout << Print(cout);
但是,编译时存在“二进制表达式的无效操作数('ostream'(又名'basic_ostream')和'ostream')”错误。
#include <iostream>
using namespace std;
ostream& Print(ostream& out) {
out << "Hello World!";
return out;
}
int main() {
cout << Print(cout);
return 0;
}
Why this doesn't work? How can I fix this? Thanks!!
为什么这不起作用?我怎样才能解决这个问题?谢谢!!
采纳答案by Potatoswatter
The syntax you might be looking for is std::cout << Print << " and hello again!\n";
. The function pointeris treated as a manipulator. A built-in operator <<
takes the pointer to Print
and calls it with cout
.
您可能正在寻找的语法是std::cout << Print << " and hello again!\n";
. 函数指针被视为操纵器。内置operator <<
函数将指针指向Print
并调用它cout
。
#include <iostream>
using namespace std;
ostream& Print(ostream& out) {
out << "Hello World!";
return out;
}
int main() {
cout << Print << " and hello again!\n";
return 0;
}
回答by 0x499602D2
Here is your second request:
这是您的第二个请求:
#include <iostream>
#include <vector>
#include <iterator>
template <class Argument>
class manipulator
{
private:
typedef std::ostream& (*Function)(std::ostream&, Argument);
public:
manipulator(Function f, Argument _arg)
: callback(f), arg(_arg)
{ }
void do_op(std::ostream& str) const
{
callback(str, arg);
}
private:
Function callback;
Argument arg;
};
template <class T>
class do_print : public manipulator<const std::vector<T>&>
{
public:
do_print(const std::vector<T>& v)
: manipulator<const std::vector<T>&>(call, v) { }
private:
static std::ostream& call(std::ostream& os, const std::vector<T>& v)
{
os << "{ ";
std::copy(v.begin(), v.end(),
std::ostream_iterator<T>(std::cout, ", "));
return os << "}";
}
};
template <class Argument>
std::ostream& operator<<(std::ostream& os, const manipulator<Argument>& m)
{
if (!os.good())
return os;
m.do_op(os);
return os;
}
template<class T>
do_print<T> Print(const std::vector<T>& v)
{
return do_print<T>(v);
}
int main()
{
std::vector<int> v{1, 2, 3};
std::cout << Print(v);
}