Answer to Question #255645 in C++ for Jack

Question #255645

Create a class which allocates the memory for a string through dynamic constructor. Overload 

  • the binary + to concatenate two strings and display it. 
  • relational operator < to compare the length of the two string.

Also rewrite this program to overload the operators as friend function.


1
Expert's answer
2021-10-23T23:31:06-0400
#include <iostream>
#include <string>


using namespace std;




class String {
public:
	String(string str) {
		len = str.length();
		chstr = new char[len];
		for (int i = 0; i < str.length(); i++) {
			chstr[i] = str[i];
			cout << chstr[i];
		}
	}


	bool operator<(const String& S) {
		return this->len < S.len;
	}
	String& operator+(const String& S) {
		String SA("");
		SA.len = this->len + S.len;
		int i = 0;
		for (; i < this->len; i++) {
			SA.chstr[i] = this->chstr[i];
		}
		for (int j = 0; j < S.len; i++, j++) {
			SA.chstr[i] = S.chstr[j];
		}
		return SA;
	}
	void print() {
		for (int i = 0; i < len;i++) {
			cout << chstr[i] << " ";
		}
	}


private:
	char* chstr;
	short int len;
};




int main() {
	String S1("pida"), S2("ras");
	String S3("");
	S3 = S1 + S2;
}






//With "Friends":

#include <iostream>
#include <string>


using namespace std;




class String {
public:
	String(string str) {
		len = str.length();
		chstr = new char[len];
		for (int i = 0; i < str.length(); i++) {
			chstr[i] = str[i];
			cout << chstr[i];
		}
	}
	friend bool operator<(const String& S0, const String& S);
	friend String& operator+(const String& S0, const String& S);
	void print() {
		for (int i = 0; i < len;i++) {
			cout << chstr[i] << " ";
		}
	}


private:
	char* chstr;
	short int len;
};


bool operator<(const String& S0, const String& S) {
	return S0.len < S.len;
}


String& operator+(const String& S0, const String& S) {
	String SA("");
	SA.len = S0.len + S.len;
	int i = 0;
	for (; i < S0.len; i++) {
		SA.chstr[i] = S0.chstr[i];
	}
	for (int j = 0; j < S.len; i++, j++) {
		SA.chstr[i] = S.chstr[j];
	}
	return SA;
}


int main() {
	String S1("pida"), S2("ras");
	String S3("");
	S3 = S1 + S2;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

Jack
26.10.21, 17:29

Thanks a ton AssignmentExpert

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS