🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

1 total messages Started by Joseph S. D. Yao Fri, 10 Oct 1986 15:55
Overloading operators on classes' ops
#342
Author: Joseph S. D. Yao
Date: Fri, 10 Oct 1986 15:55
42 lines
2255 bytes
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)
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads