home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!news.acns.nwu.edu!network.ucsd.edu!qualcom.qualcomm.com!pbender.qualcomm.com!user
- From: pbender@qualcomm.com (Paul Bender)
- Subject: Re: Automatic conversion! Can we do this?
- Message-ID: <pbender-221292142233@pbender.qualcomm.com>
- Followup-To: comp.lang.c++
- Sender: news@qualcomm.com
- Nntp-Posting-Host: pbender.qualcomm.com
- Organization: Qualcomm, Inc., San Diego, CA
- References: <1h7sq8INNr7e@function.mps.ohio-state.edu>
- Date: Tue, 22 Dec 1992 22:33:17 GMT
- Lines: 49
-
- In article <1h7sq8INNr7e@function.mps.ohio-state.edu>,
- ren@function.mps.ohio-state.edu (Liming Ren) wrote:
- >
- > I wrote a string class and overloaded operator + to achive the function
- > of strcat(). It is my understanding that the compiler will do the conversion
- > from char * to string using the function I supplied. What is strange is I can
- > do:
- >
- > string a, b("Merry");
- > a=b+" Chrismas";
- > a="C" + b;
- >
- > But I can't do: a="Merry" + " Chrismas";
- > The compiler complains that "pointer +pointer" and the conversion does not
- > happen. I tried to overload + with (char*, char*). The compiler did not
- > allow me. HERE is the class:
- >
- > class string{
- > char *str;
- > int size;
- > public:
- > string() {str=new char[10]; size=9;}
- > string(const char *p){ str=strdup(p); size=strlen(p);}
- > string(const string& s){str=strdup(s.str); size=s.size;}
- > ~string(){delete [] str;}
- > string& operator=(const string&s){/*body*/ }
- > friend string operator+(const string&,const string&){/*body*/}
- > };
- >
- > main()
- > {
- > string a;
- > a="Merry" +" Chrismas";
- > }
- >
- > It seems to me the compiler has no clue what is going on if I supply two
- > pointers. It needs at least one operand to be string to invoke the
- > overloaded + on string class. Is there a way to overcome this?
- >
- >
- > Merry Christmas!
-
- First, char* is a built in type. As such operator+(char*, char*) exists in
- some sense (although it is not legal to use it). Therefore, there is no
- need for the compiler to look any further. In addition, you cannot
- overload it as you would like since it already exists. IMHO, this is good,
- since overloading these operators (+,-,*,/) in that manner (having them
- return a value that is different from either of arguments) would lead to
- chaos.
-