The MyString class There are three data members to be written (in the private: a
ID: 3630563 • Letter: T
Question
The MyString class
There are three data members to be written (in the private: access method):
• a pointer to a char. I'll refer to this data member as the string array pointer. It will be used to dynamically allocate an array of char (the string array) that will store a C string.
• an integer used to keep track of the number of valid characters that can be stored in the string array (not counting the null character. I'll refer to this data member as the string capacity. The string capacity will always be a multiple of 16 bytes (16, 32, 48, etc.). The actual size of the string array will always be equal to the string capacity plus one (to account for the null character at the end of the string).
• an integer used to store the current size or length of the C string stored in the string array. I'll refer to this data member as the string size.
The constructors:
• MyString::MyString()
This "default" constructor for the MyString class should initialize a new MyString object to a "null string". The required logic is:
1. Set the string size for the new object to 0.
2. Set the string capacity for the new object to 16.
3. Use the string array pointer for the new object to allocate an array of char. The size of the new string array should be the string capacity plus one.
4. Either copy a null string literal ("") into the string array using strcpy() or set the first element of the string array to a null character ('').
• MyString::MyString(const char* s)
This constructor for the MyString class should initialize a new MyString object to the C string s. The required logic is:
1. Set the string size for the new object to the length of the C string s.
2. Set the string capacity for the new object to the next multiple of 16 that is greater than the string size
3. Use the string array pointer for the new object to allocate an array of char. The size of the new string array should be the string capacity plus one.
4. Copy the C string s into the string array.
Explanation / Answer
MyString::MyString()
{
capacityStr = 16;
str = new char[capacityStr + 1];
lengthStr = 0;
str[0] = ''; // append null char
}
MyString::MyString(const char * newStr)
{ // init char array
lengthStr = strlen( newStr);
if (_length < 16)
capacityStr = 16;
else
capacityStr = _length;
str = new char[_capacity + 1];
// copy chars
int i = 0;
while ( newStr[i]!= '')
{
str[i]= newStr[i];
i++;
}
str[lengthStr] = ''; //End of string
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.