【问题标题】:invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'ostream')二进制表达式的无效操作数 ('ostream' (aka 'basic_ostream<char>') 和 'ostream')
【发布时间】:2013-11-17 09:29:31
【问题描述】:

我正在努力

cout &lt;&lt; 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;
}

为什么这不起作用? 我怎样才能解决这个问题?谢谢!!

【问题讨论】:

    标签: c++


    【解决方案1】:

    您可能正在寻找的语法是std::cout &lt;&lt; Print &lt;&lt; " and hello again!\n";。函数 pointer 被视为操纵器。内置的operator &lt;&lt; 获取指向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;
    }
    

    【讨论】:

    • 谢谢!如果我想为“打印”提供参数怎么办?说“打印”被定义为“ostream& Print(vector &v)”?
    • @JASON 然后你需要定义你自己的操纵器:一个返回一个实现operator &lt;&lt;的对象的函数。
    • @JASON Bedtime for me,试试谷歌或问其他问题。
    【解决方案2】:

    这是您的第二个请求:

    #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);
    }
    

    【讨论】:

    • 这段代码除了可能做他想做的事情之外,还能做什么。
    猜你喜欢
    • 2017-03-12
    • 2021-09-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2019-07-10
    • 1970-01-01
    • 2021-08-20
    • 1970-01-01
    相关资源
    最近更新 更多