jsdy@hadron.UUCP (Joseph S. D. Yao) (10/10/86)
I tried to do something that I thought would work in C++. I think
I understand why it didn't work in C++ the implementation, but am
wondering whether I had it right in C++ the language.
Theoretically, one should be able to overload an operator with a
different routine for different type arguments. Char and int should
be different types, despite automatic promotion of constants and
function and operator arguments, right?
[Please forgive format-for-brevity in the following.]
#include <stream.h>
main(){ char ch = 'z'; cout << ch << "\n"; }
prints 122, of course, as the manual and comments say it should.
Adding AFTER this:
ostream &operator<<(ostream &s, char c) {
static char str[2] = "\0"; *str = c; return(s << str); }
gives NO CHANGE in function, and NO error message. Well, of course,
the C++ compiler hasn't seen the new overloaded operator yet. BUT
when I move the above function before main(), I get:
<< defined both as operator <<() and ostream::operartor <<()
which is supposed to be legal! (unless the args' types are the same.)
I am assuming that the implementation is treating chars as ints; but
I think I should be able to do this in the language. Comments?
By the way: ostream's operator << is defined for:
const char *, int, long, double, const streambuf &,
const whitespace &, const common &;
but note that istream's >> operator is defined for:
char *, char &, short &, int &, long &, float &, double &,
streambuf &, whitespece &, common &;
so it appears here that char is not being confused with int!
--
Joe Yao hadron!jsdy@seismo.{CSS.GOV,ARPA,UUCP}
jsdy@hadron.COM (not yet domainised)