2016-11-20 139 views
-3

这个问题上有一些帖子,但我认为这是最简单的例子之一,希望能够澄清关于cout和初始化的一些事情。不能绑定'std :: ostream {aka std :: basic_ostream <char>}'左值为'std :: basic_ostream <char> &&'

所以此工程:

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

什么给?

+0

'std :: cout << a' does *** not *** invoke the'operator <<'member function。第一个代码编译的唯一原因是因为它是[最令人头疼的解析](https://en.wikipedia.org/wiki/Most_vexing_parse)。 –

+0

很高兴知道!你能解释一点吗? – ethanabrooks

回答

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<<功能的工作方式。你将不得不使用

A a; 
    a << std::cout; 

operator<<功能需要一个非成员函数才能使用:

A a; 
    std::cout << a; 

my answer to another SO post明白为什么。

相关问题