【问题标题】:cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’无法将‘std::ostream {aka std::basic_ostream<char>}’左值绑定到‘std::basic_ostream<char>&&’
【发布时间】:2016-11-20 02:35:28
【问题描述】:

已经有几篇关于这个主题的帖子,但我认为这是最简单的例子之一,希望它能澄清一些关于 cout 和初始化的事情。

所以这行得通:

class A {
  public:
    std::ostream& operator<< (std::ostream& os) {
      return os;  
    }
};

class B {
    std::ostream& operator<< (std::ostream& os) {
      A a(); //        <-- LOOK
      std::cout << a;
      return os;  
    }
};

但如果我只是将A a() 改为A a

class A {
  public:
    std::ostream& operator<< (std::ostream& os) {
      return os;  
    }
};

class B {
    std::ostream& operator<< (std::ostream& os) {
      A a; //        <-- LOOK
      std::cout << a;
      return os;  
    }
};

它抛出:

nvcc main.cpp util.cpp -o main -lcublas -std=c++11
In file included from main.cpp:9:0:
cout-test.hpp: In member function ‘std::ostream& B::operator<<(std::ostream&)’:
cout-test.hpp:21:20: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
       std::cout << a;
                    ^
In file included from /usr/include/c++/4.8/iostream:39:0,
                 from main.cpp:5:
/usr/include/c++/4.8/ostream:602:5: error:   initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = A]’
     operator<<(basic_ostream<_CharT, _Traits>&& __os, const _Tp& __x)
     ^
make: *** [main] Error 1

如果我将A a 设为类成员,我会得到同样的错误:

class B {
    A a; //        <-- LOOK
    std::ostream& operator<< (std::ostream& os) {
      std::cout << a;
      return os;  
    }
};

什么给了?

【问题讨论】:

  • std::cout &lt;&lt; a 调用operator&lt;&lt; 成员函数。第一个代码编译的唯一原因是因为它是a most vexing parse
  • 很高兴知道!你能再解释一下吗?

标签: c++ initialization cout


【解决方案1】:

第一个案例

  A a();

不构造对象。它声明了一个函数。这个解析问题被称为The Most Vexing Parse

  A a();
  std::cout << a;

有效,因为在这种情况下a 被转换为bool。请参阅 Why does pointer to int convert to void* but pointer to function convert to bool? 为什么会这样。

第二种情况

  A a;
  std::cout << a;

由于您定义operator&lt;&lt; 函数的方式而不起作用。你必须使用

  A a;
  a << std::cout;

operator&lt;&lt; 函数必须是非成员函数才能使用:

  A a;
  std::cout << a;

请参阅my answer to another SO post 了解原因。

【讨论】:

    猜你喜欢
    • 2014-08-27
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    相关资源
    最近更新 更多