The Assignment Functions. McGraw-Hill The Complete Reference Fourth Edition
Reklama
Reklama
C h a p t e r 3 9 : I n t e g r a t i n g N e w C l a s s e s : A C u s t o m S t r i n g C l a s s
941
The Assignment Functions
You can assign a StrType object a string in two ways. First, you can assign another StrType object to it. Second, you can assign it a quoted string. The two overloaded operator=( ) functions that accomplish these operations are shown here:
// Assign a StrType object to a StrType object.
StrType StrType::operator=(StrType &o)
{
StrType temp(o.p); if(o.size > size) { delete [] p; // free old memory try { p = new char[o.size];
} catch (bad_alloc xa) { cout << "Allocation error\n"; exit(1);
} size = o.size;
} strcpy(p, o.p); strcpy(temp.p, o.p);
} return temp;
// Assign a quoted string to a StrType object.
StrType StrType::operator=(char *s)
{ int len = strlen(s) + 1; if(size < len) { delete [] p; try { p = new char[len];
} catch (bad_alloc xa) { cout << "Allocation error\n"; exit(1);
Stiahnuť
Reklama