Grant Rogers
asked on
Overloading the insertion operator
Hello, I have found something strange. I am using Visual C++ 6.0 SP6 so I am not sure if it is a bug with this or what but here goes.
I wrote a small piece of code:
#include <iostream>
int main()
{
const char *pMessage = "Hello World\n";
std::cout.operator<<(pMess age); // Prints out the address of pMessage
std::cout << pMessage; // Prints out the message
return 0;
}
When I trace through the code the first call using cout matches the signature as const void * and the second one matches to basic_ostream<_E, _Tr>& _O, const _E *_X in this case: basic_ostream<char, char_traits<char>>& _O, const char *_X as far as I am aware.
What I don't understand is why operator<<() is using a different signature from plain << I thought they are synonymous. Can anyone tell me why? Is it a bug to do with Microsofts C++ compiler?
Thanks
Grant
I wrote a small piece of code:
#include <iostream>
int main()
{
const char *pMessage = "Hello World\n";
std::cout.operator<<(pMess
std::cout << pMessage; // Prints out the message
return 0;
}
When I trace through the code the first call using cout matches the signature as const void * and the second one matches to basic_ostream<_E, _Tr>& _O, const _E *_X in this case: basic_ostream<char, char_traits<char>>& _O, const char *_X as far as I am aware.
What I don't understand is why operator<<() is using a different signature from plain << I thought they are synonymous. Can anyone tell me why? Is it a bug to do with Microsofts C++ compiler?
Thanks
Grant
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
std::operator<<(cout,pMess age); //your style
std::cout.operator<<(pMess age); // this is only for character
std::cout.operator<<(*(pMe ssage)); // this u will get character H
//please remember that the style to overload operator are not the same
for example
you want to overload
a++;
++B;
//prefix and postfix it has different style
// if i am not mistaken one is ++ operator() and another is operator()++
hope this clear
std::cout.operator<<(*(pMe
//please remember that the style to overload operator are not the same
for example
you want to overload
a++;
++B;
//prefix and postfix it has different style
// if i am not mistaken one is ++ operator() and another is operator()++
hope this clear
sorry is operator++()
>>// if i am not mistaken one is ++ operator() and another is operator()++
A correction:
operator ++ () and operator ++ (int)
_novi_
A correction:
operator ++ () and operator ++ (int)
_novi_
ok thanks.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi thanks for the info. I now understand why my call was producing the result it did and how to retify this.
welcome :-)
see:
http://www.edm2.com/0512/introcpp5.html