편집 : Mike Seymour의 의견에 따라 operator std::string() const;
을 operator char *() const;
으로 바꿔 그에 따라 구현을 변경했습니다. 이것은 암시 적 캐스팅을 허용하지만 어떤 이유에서든 unsigned long int 연산자가 char * 연산자보다 우선합니다.이 연산자는 옳은 느낌이 들지 않습니다 ... 또한 char *와 같은 불쾌한 C 요소를 노출하고 싶지 않습니다. 클래스, 때 std :: string. 내 CustomizedInt 클래스가 원하는 기능을 지원하기 위해 몇 가지 요소를 상속해야한다는 생각이 들었습니다. 아무도 std::basic_string
에 관한 마이크의 의견을 자세히 설명해 주시겠습니까? 내가 제대로 이해하는지 모르겠다.C++ 암시 적 변환 연산자 우선 순위
#include <string>
#include <sstream>
#include <iostream>
class CustomizedInt
{
private:
int data;
public:
CustomizedInt() : data(123)
{
}
operator unsigned long int() const;
operator std::string() const;
};
CustomizedInt::operator unsigned long int() const
{
std::cout << "Called operator unsigned long int; ";
unsigned long int output;
output = (unsigned long int)data;
return output;
}
CustomizedInt::operator std::string() const
{
std::cout << "Called operator std::string; ";
std::stringstream ss;
ss << this->data;
return ss.str();
}
int main()
{
CustomizedInt x;
std::cout << x << std::endl;
return 0;
}
"123 INT 긴 호출 연산자 부호"인쇄 :
나는이 코드 조각이있다. 내 질문은 다음과 같습니다.
- unsigned long int 연산자를 제거한 후에 x를 std :: string으로 명시 적으로 변환해야하는 이유는 무엇입니까? 왜 암시 적 캐스트 연산자 (std :: string)를 직접 호출하지 않습니까?
- 어떤 암시 적 캐스트가 허용되며 우선 순위는 무엇인지 설명하는 설명서가 있습니까? unsigned long int 연산자와 함께이 클래스에 unsigned int 연산자를 추가하면 < < 연산자에 대한 컴파일러 오류가 발생합니다.
- 또한 이러한 연산자를 정의하는 것이 가난한 관행이지만 관련된 경고 사항을 완전히 이해하고 있는지 확신 할 수 없습니다. 누군가가 그들을 윤곽을 그릴 수 있을까요? 공용 메서드 ToUnsignedLongInt 및 ToString을 정의하는 것이 더 나은 방법일까요? 내가 운영자 부호없는 긴 INT를 제거한 후
관련이 있습니다 : [문자열로 암시 적 변환을 통해 객체를 스트리밍 할 때의 오버로드 해결 실패] (http://stackoverflow.com/questions/6677072/overload-resolution-failure-when-streaming-object-via-implicit-conversion -to-str) –
@Als : 천천히 가져 가자. 아직 템플릿으로 들어가기 위해 준비가 안됐다. :) –