Files
BasicsOfComputerSoftwareEng…/OOP/04/Exercise02.cpp
2023-03-21 13:26:26 +08:00

120 lines
2.7 KiB
C++

#include <iostream>
class String {
private:
char *str;
public:
String();
String(String &otherStr);
String(char *otherStr);
~String();
bool operator==(String &otherStr);
bool operator>(String &otherStr);
bool operator<(String &otherStr);
String& operator=(String& otherStr);
String& operator+(String& otherStr);
char *getStrPtr();
void printOut();
};
String::String() {
this->str = NULL;
}
String::String(String &otherStr) {
this->str = new char[strlen(otherStr.getStrPtr()) + 1];
strcpy(this->str, otherStr.getStrPtr());
}
String::String(char *otherStr) {
this->str = new char[strlen(otherStr) + 1];
strcpy(this->str, otherStr);
}
String::~String() {
if (this->str != NULL) {
delete[] this->str;
}
}
bool String::operator==(String &otherString) {
if (this->str == NULL) {
if (otherString.getStrPtr() == NULL) {
return true;
}
else {
return false;
}
}
return (strcmp(this->str, otherString.getStrPtr()) == 0);
}
bool String::operator>(String &otherString) {
return strcmp(this->str, otherString.getStrPtr()) > 0;
}
bool String::operator<(String &otherString) {
return strcmp(this->str, otherString.getStrPtr()) < 0;
}
String& String::operator+(String &otherString) {
String* tmp = new String(new char[strlen(this->getStrPtr()) + strlen(otherString.getStrPtr()) + 1]);
strcpy(tmp->getStrPtr(), this->getStrPtr());
strcat(tmp->getStrPtr(), otherString.getStrPtr());
return *tmp;
}
String& String::operator=(String &otherString) {
if (this->str != NULL) {
delete[] this->str;
}
this->str = new char[strlen(otherString.getStrPtr()) + 1];
strcpy(this->str, otherString.getStrPtr());
return *this;
}
char *String::getStrPtr() {
return this->str;
}
void String::printOut() {
std::cout << this->str << std::endl;
}
int main() {
char *str1 = new char[10];
char *str2 = new char[10];
std::cout << "String 1: ";
std::cin >> str1;
std::cout << "String 2: ";
std::cin >> str2;
String string1(str1);
String string2(str2);
String string3 = string2;
string1.printOut();
string2.printOut();
string3.printOut();
string3 = string1 + string2;
string3.printOut();
(string1 + string2).printOut();
if (!(string1 > string2)) {
std::cout <<"String1 NOT > String2" << std::endl;
}
if (string1 < string2) {
std::cout <<"String1 < String2" << std::endl;
}
if (string1 == string3) {
std::cout << "String1 = String3" << std::endl;
}
if (!(string2 == string3)) {
std::cout << "String2 != String3" << std::endl;
}
return 0;
}