2010-02-10 2 views
12

나는 클래스에 다음 코드가 있습니다연산자 문자열() (일부 코드)은 무엇을합니까?

operator string() { 
     return format("CN(%d)", _fd); 
} 

을 그리고이 연산자가 무엇을 알고 싶어.

나는 보통 문자열 사업자 익숙 :

bool operator==(const string& c1, const string& c2); 
bool operator!=(const string& c1, const string& c2); 
bool operator<(const string& c1, const string& c2); 
bool operator>(const string& c1, const string& c2); 
bool operator<=(const string& c1, const string& c2); 
bool operator>=(const string& c1, const string& c2); 
string operator+(const string& s1, const string& s2); 
string operator+(const Char* s, const string& s2); 
string operator+(Char c, const string& s2); 
string operator+(const string& s1, const Char* s); 
string operator+(const string& s1, Char c); 
string& operator+=(const string& append); 
string& operator+=(const Char* append); 
string& operator+=(const Char append); 
ostream& operator<<(ostream& os, const string& s); 
istream& operator>>(istream& is, string& s); 
string& operator=(const string& s); 
string& operator=(const Char* s); 
string& operator=(Char ch); 
Char& operator[](size_type index); 
const Char& operator[](size_type index) const; 

...하지만이 하나?

답변

29
operator Type() { ... } 

는 (암시 적) 변환 연산자이다. 클래스 Animaloperator string() 다음 코드를 구현하는 경우 예를 들어,

Animal a; 
... 
do_something_with ((string)a); 

좀 더 예제 http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.doc/language/ref/cplr385.htm를 참조 뭔가

do_something_with ((Animal::operator string)(&a)); 

처럼 될 것이다.

+1

+1은 적절한 이름으로 변환 연산자를 나타냅니다. –

+0

좋은 예제는 타입의 객체가'if (object) {...} else {...}'에서 사용될 수 있도록 해주는'operator bool() {...}'입니다. 컨테이너 유형에서 비어 있지 않은 것이 사실임을 의미하는 것으로 구현 될 수 있습니다. – wich

+0

@wich :'operator bool'은 예상치 못한 동작을 줄 수 있습니다. http://stackoverflow.com/questions/2145931/why-is-operator-bool-invoked-when-i-cast-to-long. – kennytm

1

예를 들어 현재 개체의 문자열 represantation을 반환하는 경우. 콘솔에 인쇄합니다.

+1

보다 구체적으로 말하면, 'string'유형으로 변환하기위한 변환 연산자입니다. 다른 유형을 대상으로하는 전환 연산자도 만들 수 있습니다. –

7

캐스트 연산자가 오버로드됩니다.

operator string(); 

정의 된 클래스는 문자열로 캐스트 될 수 있습니다.

+1

캐스팅과 관련이 없으며 캐스팅으로 인해 발생할 수있는 유형 변환이 다른 문제입니다. – wich

-2

이는 십진수 형식의 문자열로 변환 된 것으로 보입니다.

1

자동 변환 연산자입니다. 이 클래스는 암시 적으로 문자열로 변환 될 수 있습니다. 이 link 몇 가지 예를 들어 당신을 도울 수 있습니다.

+0

링크 (http://www.codeguru.com/cpp/tic/tic0131.shtml)가 작동하지 않습니다. – dpatru

관련 문제