Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Overloading operators on classes' ops

1 view
Skip to first unread message

Joseph S. D. Yao

unread,
Oct 10, 1986, 11:55:12 AM10/10/86
to
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}
js...@hadron.COM (not yet domainised)

0 new messages