-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;
}
};
什麼給?
'std :: cout << a' does *** not *** invoke the'operator <<'member function。第一個代碼編譯的唯一原因是因爲它是[最令人頭疼的解析](https://en.wikipedia.org/wiki/Most_vexing_parse)。 –
很高興知道!你能解釋一點嗎? – ethanabrooks