Create a class named Text whose objects store lists of words. The list of words will be represented using a dynamically allocated array of string variables where each word in the list is stored in a separate string variable array. The size of the array must always reflect the exact number of words stored in the Text object. Include the following:
Default constructor that will create a Text object with zero words.
Overloaded << operator that will output the Text object. Each word must be separated by a single space.
Overload + operator that will concatenate two Text objects.
Overload + operator that will concatenate two Text object with a string object.
Overload + operator that will concatenate two Text object with a c-string. Note: the argument type for a c-string is const char*.
Since you are using dynamic variables in this class, you must also include the required member functions to properly handle memory allocation issues.
Write a test program that includes the following lines of C++ code (at minimum):
This was the lab project that I was given. I wrote code and I have had it reviewed by my classmates and TA’s, but there are still errors and we can’t come to a conclusion as to what the error in the code is. I was wondering if anyone was able to spot what we haven’t been able uncover. The code below is the code that I have written.
This code is the first part I wrote including the classes. I have named it text.h.
Text operator + (Text A, Text B){
Text temp;
temp.value=new string [A.length+B.length];
for(int i=0;i<A.length;i++){
temp.value[i]=A.value[i];
}
// for(int i=A.length;i<B.length;i++){ // bad code
for(int i=A.length;i<B.length+A.length;i++){// may work better
temp.value[i]=A.value[i];
}
or this...
1 2 3 4 5 6 7 8 9
// uninitialized value used in copy ctor
Text::Text(Text& object){ // const Text& is usual choice here
value= new string[length];// what does length= here?
length = object.length;// you probably meant for this line to be first
for(int i=0;i<length;i++){
value[i]=object.value[i];
}
}
If your TA couldn't find those then he should be taking your class.
Other things I see are just errors, which may not affect Text values.
A memory leak:
1 2 3 4 5 6 7 8 9 10
Text& Text::operator = (Text& object){
if(this != &object) {
value= new string[object.length];// release memory before overwriting this pointer value!
length = object.length;
for(int i=0;i<length;i++){
value[i]=object.value[i];
}
}
return *this;
}
I see you may have other issues too (that Text& operator + (Text A, const char* B) function looks like you are having trouble there ).
But I'll stop there.