#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
class MyStr {
int _count = 0;
int length{ 0 };
char* buff{ nullptr };
static int count;
public:
MyStr() : length(0), buff(nullptr) {
_count = count++;
cout << " MyStr default constr. " << _count << endl;
}
MyStr(const char* init_val) : length(0), buff(nullptr){
_count = count++;
cout << " MyStr( char * ) constr. " << _count << endl;;
if ((init_val == nullptr) || (*init_val == '\0')) {
return;
}
length = strlen(init_val);
buff = new char[length + 1];
strcpy(buff, init_val);
}
MyStr(const MyStr& other) : length(0), buff(nullptr) {
_count = count++;
cout << " MyStr( ) copy_ctor " << _count << endl;
if (other.length == 0) {
return;
}
this->length = other.length;
this->buff = new char[length + 1];
strcpy(buff, other.buff);
}
~MyStr() {
cout << " MyStr( ) DTOR " << _count << endl;
delete[] buff;
}
int size() { return length; }
MyStr& operator= (const MyStr& other) {
if (other.length == 0) {
delete[] buff;
buff = nullptr;
length = 0;
}
else {
delete[] buff;
buff = nullptr;
length = other.length;
buff = new char[length + 1];
strcpy(buff, other.buff);
}
return *this;
}
friend MyStr operator+(const MyStr& s1, const MyStr& s2);
friend ostream& operator<< (ostream&, const MyStr&);
char& operator[] (int index) {
return buff[index];
}
};
int MyStr::count = 0;
MyStr operator+(const MyStr& s1, const MyStr& s2) {
MyStr ret;
if ((s1.length == 0) && (s2.length == 0)) {
return ret;
}
else if (s1.length == 0){
return s2;
}
else if (s2.length == 0) {
return s1;
}
else {
ret.length = s1.length + s2.length;
ret.buff = new char[ret.length+1];
strcpy(ret.buff, s1.buff);
strcat(ret.buff, s2.buff);
return ret;
}
}
ostream& operator<< (ostream& os, const MyStr& s) {
if (s.length == 0) {
return os;
}
else {
os << s.buff;
return os;
}
return os;
}
int main() {
string s = "Hello";
cout << s.size() << endl;
MyStr a = "\0";
MyStr b = "\0";
MyStr c;
c = a + b;
cout << c;
/*
MyStr c = a;
///////////////
MyStr c2;
c2 = a;
///////////////
cout << c << endl;
*/
return 0;
}