Last edited on
thanks all...
Now I am overloading the operator+. The first call is like this:
String operator+(char *, String&).
I want to combine char* and String& into a char* type, without use strcat().
what is the best approach to this ?
Thanks
I've tried this
strcpy(buf,char*); // ok this is fine BUT
strcpy(buf,String&); // this will overwrite the first
and why cant you use strcat?
strcat(char*,String&) will modify char*, I don't want that.
Is there a way for strcpy to append instead of overwrite ?
you cant get the string& into the char* without modifying it... and having strcpy append (which it cant do) is exactly what strcat does
You normally want to implement operator+ in terms of operator+=.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class String
{
public:
String(const char* cStr);
String& operator += (const char*) ;
String& operator += (const String&) ;
};
String& String::operator+=(const char*cStr)
{
unsigned cStrLen = std::strlen(cStr) ;
char* newBuf = new[length + cStrLen + 1] ;
std::strcpy(newBuf, buf) ;
std::strcpy(newBuf+length, cStr);
length += cStrLen ;
delete [] buf ;
buf = newBuf ;
return *this ;
}
inline String operator+(const char* cStr, const String& str)
{
String result(cStr) ;
return result += str ; // C++11: return std::move(result+=str) ;
}
inline String operator+(String str, const char* cStr)
{
return str += cStr ;
}
|
Last edited on
unfortunately it's the other way...char* into string& !
sorry if I sound so 'lost', but i am pretty new to all this.
I already have this
char * buf = new char[strlen(char*) + strlen(string&)];
I am looking for a way to combine char* and string& into newCh* so I can do this.
strcpy(buf, newCh);
thanks cire....this is what I was looking for:
std::strcpy(newBuf+length, cStr);