I must admit it is an interesting isuuse, and of course it cannot be seen frequently.
I'll borrow explanation from Bjarne Stroustrup:
"A member
function X : : operator T(), where T is a type name, defines a conversion from X to T."
Code:
class Tiny {
char v;
void assign(int i) { if (i&~077) throw Bad_ range() ; v=i; }
public:
class Bad_ range{ };
Tiny(int i) { assign(i) ; }
Tiny& operator=(int i) { assign(i) ; return *this; }
operator int() const { return v; } / / conversion to int function
};
The range is checked whenever a Tiny is initialized by an int and whenever an int is assigned to
one. No range check is needed when we copy a Tiny, so the default copy constructor and assignment
are just right.
To enable the usual integer operations on Tiny variables, we define the implicit conversion from
Tiny to int, Tiny: : operator int(). Note that the type being converted to is part of the name of the
operator and cannot be repeated as the return value of the conversion function:
Code:
Tiny: : operator int() const { return v; } / / right
int Tiny: :operator int() const { return v; } / / error
Normally, if you give cout a pointer, it prints an address. But if the pointer is type char *, cout displays the pointed-to string. If you want to see the address of the string, you have to type cast the pointer to another pointer type, such as int *
for example:
Code:
#include<iostream>
using namespace std;
int main()
{
char str[]="micko";
cout<<str;
cout<<(int*)str;
}
You see the difference.
Now the question is why this code:
will print hexadecimal address (I've never figured out should I use the hexadecimal or just hexadecimal in this context )
and this code
Code:
cout << (char*)test;
will print string.
To answer this let's call a little assembly in help:
First code will produce something like this:
Code:
MyClass test;
0043237E lea ecx,[test]
00432381 call MyClass::MyClass (42E677h)
cout <<test;
00432386 lea ecx,[test]
00432389 call MyClass::operator char * (42E528h)
0043238E push eax
0043238F mov ecx,offset std::cout (49D244h)
00432394 call std::basic_ostream<char,std::char_traits<char> >::operator<< (42E299h)
Second code will produce something like this:
Code:
MyClass test;
0043136E lea ecx,[test]
00431371 call MyClass::MyClass (42D672h)
cout <<(char*)test;
00431376 lea ecx,[test]
00431379 call MyClass::operator char * (42D523h)
0043137E push eax
0043137F push offset std::cout (49B254h)
00431384 call std::operator<< (42EE87h)
As you can notice that different versions of operator<< are called.
So I can assume that the reason (again the ) is impicit conversion which happens because of member function operator char*();
Why it is different in Linux I don't have any clue, so I'll take this opportunity to ask guys with a lot more experience than me and especially with experience in Linux to try to asnwer this together.
I'm looking forward to all constructive posts on this thread.
Cheers!
Micko