2016-11-20 7 views
-3

이 주제에 대한 몇 가지 게시물이 있지만 가장 간단한 예제 중 하나라고 생각합니다. 잘하면 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; 
    } 
}; 

무엇을 제공합니까?

+0

'std :: cout << a'는 *** 연산자가 아닌'operator <<'함수를 호출합니다. 첫 번째 코드가 컴파일되는 유일한 이유는 [가장 고생하는 구문] (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<< 기능을 정의하는 방식으로 작동하지 않습니다. 당신이 사용하기 위해 operator<< 함수는 비 멤버 함수 할 필요가

A a; 
    a << std::cout; 

를 사용해야합니다 :

A a; 
    std::cout << a; 

이유를 이해하기 my answer to another SO post를 참조하십시오.