2016-11-20 340 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明白爲什麼。

相關問題