이 주제에 대한 몇 가지 게시물이 있지만 가장 간단한 예제 중 하나라고 생각합니다. 잘하면 cout 및 초기화에 대한 몇 가지 사항을 명확히 설명합니다.'std :: ostream {aka std :: basic_ostream <char>}'lvalue to '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;
}
};
그것은 예외 : 나는 A a
을 할 경우
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
나는 같은 오류가 반원 :
class B {
A a; // <-- LOOK
std::ostream& operator<< (std::ostream& os) {
std::cout << a;
return os;
}
};
무엇을 제공합니까?
'std :: cout << a'는 *** 연산자가 아닌'operator <<'함수를 호출합니다. 첫 번째 코드가 컴파일되는 유일한 이유는 [가장 고생하는 구문] (https://en.wikipedia.org/wiki/Most_vexing_parse)이기 때문입니다. –
알아두면 좋습니다! 좀 더 설명해 주시겠습니까? – ethanabrooks