home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #31 / NN_1992_31.iso / spool / comp / lang / cplus / 18326 < prev    next >
Encoding:
Text File  |  1992-12-22  |  2.2 KB  |  63 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!zaphod.mps.ohio-state.edu!news.acns.nwu.edu!network.ucsd.edu!qualcom.qualcomm.com!pbender.qualcomm.com!user
  3. From: pbender@qualcomm.com (Paul Bender)
  4. Subject: Re: Automatic conversion! Can we do this?
  5. Message-ID: <pbender-221292142233@pbender.qualcomm.com>
  6. Followup-To: comp.lang.c++
  7. Sender: news@qualcomm.com
  8. Nntp-Posting-Host: pbender.qualcomm.com
  9. Organization: Qualcomm, Inc., San Diego, CA
  10. References: <1h7sq8INNr7e@function.mps.ohio-state.edu>
  11. Date: Tue, 22 Dec 1992 22:33:17 GMT
  12. Lines: 49
  13.  
  14. In article <1h7sq8INNr7e@function.mps.ohio-state.edu>,
  15. ren@function.mps.ohio-state.edu (Liming Ren) wrote:
  16. > I wrote a string class and overloaded  operator + to achive the function
  17. > of strcat(). It is my understanding that the compiler will do the conversion
  18. > from char * to string using the function I supplied. What is strange is I can
  19. > do:
  20. > string a, b("Merry");
  21. > a=b+" Chrismas";
  22. > a="C" + b;
  23. > But I can't do:   a="Merry" + " Chrismas";
  24. > The compiler complains that "pointer +pointer" and the conversion does not 
  25. > happen. I tried to overload + with (char*, char*). The compiler did not 
  26. > allow me. HERE is the class:
  27. > class string{
  28. >   char *str;
  29. >   int size;
  30. >  public:
  31. >   string()  {str=new char[10]; size=9;}
  32. >   string(const char *p){ str=strdup(p); size=strlen(p);}
  33. >   string(const string& s){str=strdup(s.str); size=s.size;}
  34. >   ~string(){delete [] str;}
  35. >   string& operator=(const string&s){/*body*/    }
  36. >   friend string operator+(const string&,const string&){/*body*/}
  37. > };
  38. > main()
  39. > {
  40. >   string a;
  41. >   a="Merry" +" Chrismas";
  42. > }
  43. > It seems to me the compiler has no clue what is going on if I supply two
  44. > pointers. It needs at least one operand to be string to invoke the
  45. > overloaded + on string class. Is there a way to overcome this?
  46. > Merry Christmas!
  47.  
  48. First, char* is a built in type.  As such operator+(char*, char*) exists in
  49. some sense (although it is not legal to use it).  Therefore, there is no
  50. need for the compiler to look any further.  In addition, you cannot
  51. overload it as you would like since it already exists.  IMHO, this is good,
  52. since overloading these operators (+,-,*,/) in that manner (having them
  53. return a value that is different from either of arguments) would lead to
  54. chaos.
  55.