Construct the String class to describe a string of characters, with the following functions:
constructor, destructor, copy constructor, assignment operator function
Define operator to add two strings (concatenate two strings)
Functions that define comparison operations !=,==,>,>=,<,<=
Define input and output operators for a string
Functions that allow to assign/get (write/read) the value of a certain element in the Array
Write a main program using the above String class
#include<iostream>
#include<string>
using namespace std;
class String{
private:
string characters;//string of characters
public:
String(){}
//constructor
String(string characters) {
this->characters = characters;
}
//copy constructor
String(String& stringOther) {
this->characters = stringOther.characters;
}
//destructor
~String(){}
//assignment operator function
String operator=(String & stringOther)
{
this->characters=stringOther.characters;
return *this;
}
//Define operator to add two strings (concatenate two strings)
String operator+(String & stringOther)
{
return this->characters+stringOther.characters;
}
//Functions that define comparison operations !=,==,>,>=,<,<=
bool operator==(const String& rhs) const {
return this->characters == rhs.characters;
}
bool operator!=(const String& rhs) const {
return !(*this == rhs);
}
bool operator<=(const String& rhs) const {
return !(rhs < *this);
}
bool operator>(const String& rhs) const {
return rhs < *this;
}
bool operator<(const String& rhs) const {
return rhs.characters.compare(this->characters)<0;
}
bool operator>=(const String& rhs) const {
return !(*this < rhs);
}
//Define input and output operators for a string
friend ostream& operator<<(ostream& os,const String &str){
os <<str.characters;
return os;
}
//Functions that allow to assign/get (write/read) the value of a certain element in the Array
friend istream& operator>>(istream & strIstream, String &str){
getline(strIstream,str.characters);
return strIstream;
}
};
int main(){
//Write a main program using the above String class
String string1;
String string2;
cout<<"Enter the string 1: ";
cin>>string1;
cout<<"Enter the string 2: ";
cin>>string2;
cout<<"\nThe string 1: "<<string1;
cout<<"\nThe string 2: "<<string2<<"\n\n";
cout<<"(string1>string2): "<<(string1>string2)<<"\n";
cout<<"(string1<string2): "<<(string1<string2)<<"\n";
cout<<"(string1!=string2): "<<(string1!=string2)<<"\n";
cout<<"(string1==string2): "<<(string1==string2)<<"\n";
cout<<"(string1>=string2): "<<(string1>=string2)<<"\n";
cout<<"(string1<=string2): "<<(string1<=string2)<<"\n";
cout<<"(string1+string2): "<<(string1+string2)<<"\n";
system("pause");
return 0;
}
Comments
Leave a comment