nclass
string {
n public:
n explicit string (char *); //another constructor
n friend string operator + (const string
&, char *);
n friend string operator + (char *, const
string &);
n friend string operator + (const
string&, const string&);
n string & operator += (const string
&);
n string & operator += (char *);
n •••
n};
nstring
operator + (const string &s, char *lit) {
n char * temp = new
char[s.len+strlen(lit)+1];
n strcpy(temp, s.str);
n strcat(temp, lit);
n return string(temp);
n}
äThis approach
eliminates the creation of a temporary string “object” in the + function by explicitly using
the constructor to create
the object as part of the return statement.
When this can be done, it saves the cost of copying the object to the stack at return time.