2014-09-17 1 views
1

다음 예에서 operator <<은 문자열이 아닌 두 번 캐스팅하는 것을 선호합니까? 프리미티브가 우선 순위가 높기 때문입니까?C++ : 연산자 << 암시 적 캐스팅 우선 순위

class R { 
public: 
    R(double x) : _x(x) {} 
    operator string() {cout << "In string operator\n"; return std::to_string(_x);} 
    operator double() {cout << "In double operator\n"; return _x;} 
private: 
    double _x; 
}; 

int main() { 
    R r(2.5); 
    cout << r << endl; 
    return 0; 
} 

답변

0

왜냐하면 operator std::string()은 단순히 실행 가능하지 않기 때문입니다. basic_string의 복용 operator<< 과부하

template<class charT, class traits, class Allocator> 
basic_ostream<charT, traits>& 
operator<<(basic_ostream<charT, traits>& os, const basic_string<charT,traits,Allocator>& str); 

되고 템플릿 인수 공제 유형 R에서 템플릿 인수를 추론 할 수 없습니다. 암시 적 변환을 살펴 보지 않습니다.

이 내용은 operator doublewatching your code explode으로 주석 처리 할 수 ​​있습니다.