We are required to define a string class name string. The data members of the cl
ID: 3616688 • Letter: W
Question
We are required to define a string class name string. The data members of the class are the character array and size of the character array. There should be two constructors one is default and other should be overloaded constructor. DisplayQ is the method which display the string. Now you are required to overload+= operator This operator should allow statements like s1 += s2; where s2 is added (concatenated) to si and the result is left in s1. The operator should also permit the results of the operation to be used in other calculations, as in s3 = s1 + = s2;Explanation / Answer
#include<iostream>
#include<cassert>
class String
{
public:
String(const char * ="");
String(constString&);
~String();
const String&operator+=(const String &);
int getLength();
void Display();
private:
int size;
char* charArray;
void setString(constchar*);
};
String::String(const char*s):size(strlen(s))
{
setString(s);
}
String::String(const String ©):size(copy.size)
{
setString(copy.charArray);
}
String::~String()
{
delete [] charArray;
}
voidString::setString(const char* S)
{
charArray=new char[size+1];
assert(charArray!=0);
strcpy(charArray, S);
}
const String&String::operator += (const String &right)
{
char *tempPtr=charArray;//storing String forfurther use
size+=right.size;
charArray=new char[size+1];
strcpy(charArray, tempPtr);
strcat(charArray, right.charArray);
delete[] tempPtr;
return*this;
}
int String::getLength()
{
return size;
}
void String::Display()
{
cout<<charArray<<" ";
}
int main()
{
String s1("Cramster");
String s2("Helpfourm");
String s3("My");
String s4("Cramster");
String s5;
cout<<"String 1 = ";
s1.Display();
cout<<"String 2 = ";
s2.Display();
s1+=s2;
cout<<"String 1 += String 2 = ";
s1.Display();
cout<<" now checking the += operator with= operator ";
cout<<"String 1 = ";
s3.Display();
cout<<"String 2 = ";
s4.Display();
s5=s3+=s4;
cout<<"String3 = String 1 += String 2 =";
s5.Display();
s1.~String();
s2.~String();
s3.~String();
s4.~String();
s5.~String();
system("PAUSE");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.