#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class strtype {
	char *p;
	int len;
public:
	strtype(){};
	strtype(char *ptr);
	strtype(const strtype &s);
	strtype &operator=(strtype &ob);
	char &operator[](int i){return p[i];}
	~strtype();
	char *get(){return p;}
	int getlen(){return len;}
	strtype operator+(strtype &ob);
	int operator<(strtype &ob);
	int operator>(strtype &ob);
	int operator==(strtype &ob);
};
strtype strtype::operator+(strtype &ob)
{
	strtype temp;
	temp.len = len + ob.len;
	temp.p = new char[temp.len + 1];
	if(!p){
		cout << "メモリ割り当てエラー\n";
		exit(1);
	}
	strcpy(temp.p, p);
	strcat(temp.p, ob.p);
	return temp;
}
int strtype::operator<(strtype &ob)
{
	return strcmp(p, ob.p) < 0;
}
int strtype::operator>(strtype &ob)
{
	return strcmp(p, ob.p) > 0;
}
int strtype::operator==(strtype &ob)
{
	return strcmp(p, ob.p) == 0;
}
strtype::strtype(char *ptr)
{
	int l = strlen(ptr);
	cout << "pにメモリを割り当てる。\n";
	this->p = new char[l + 1];
	if (!p) {
		cout << "メモリ割り当てエラー\n";
		exit(1);
	}	
	strcpy(this->p, ptr);
	this->len = l;
}

strtype::strtype(const strtype &s)
{
	cout << "コピーコンストラクタ\n";
	len = s.len;
	p = new char[len];
	if (!p){
		cout << "メモリ割り当てエラー";
		exit(1);
	}
	strncpy(p, s.p,len);
}
strtype &strtype::operator=(strtype &ob)
{
	cout << "=オペレータ\n";
	if(len < ob.len){
		delete [] p;
		p = new char [ob.len];
		if (!p){
			cout << "メモリ割り当てエラー";
			exit(1);
		}
	}
	len = ob.len;
	strcpy(p, ob.p);
	return *this;
}
strtype::~strtype()
{
	cout << "pを解放する。\n";
	delete p;
}

void show(strtype x)
{
	cout << x.get() << "-長さ:" << x.getlen() << "\n";
}

int main()
{
	strtype s1("This is a test."), s2("I like C++.");
	strtype s3 = s1;
	s3 = s1;
	show(s1);
	show(s2);
	show(s3);
	for(int i = 0; i < s1.getlen(); i++){
		cout << s1[i] << " ";
	}
	cout << "\n";
	
	strtype s4 = s1 + s2;
	show(s4);
	if (s1 > s2){
		cout << "s1 > s2" << "\n";
	}
	if (s3 == s1){
		cout << "s1 == s3" << "\n";
	}
	
	return 0;
}