Myarray and Mystring

发布时间 2023-05-23 15:53:49作者: LiHaoyu

Mystring.cpp

#include <bits/stdc++.h>

using namespace std;

class Mystring
{
public:
	Mystring() : s_(NULL), len_(0), siz_(0) {} //无参构造 
	Mystring(const char* s); //有参构造 
	Mystring(const Mystring& p); //拷贝构造 
	~Mystring() { delete []s_; } //析构函数 
	
	void show(); //输出 
	Mystring& operator = (const Mystring& p); //重载 =  
	friend ostream& operator << (ostream& os, const Mystring& p); //重载cout 
	
public:
	char* s_;
	size_t len_; //字符串的长度 
	size_t siz_; //实际分配的大小	
};

Mystring::Mystring(const char* s) : s_(NULL), len_(0), siz_(0)
{
	while (s[len_ ] != 0) len_ ++ ; //计算s串的长度 
	siz_ = 2 * len_; 
	s_ = new char [siz_]; //分配空间 
	for (int i = 0; s[i] != '\0'; i ++ ) //拷贝数据 
		s_[i] = s[i]; 
}

void Mystring::show()
{
	for (int i = 0; i < len_; i ++ ) cout << s_[i];
	puts("");
}

Mystring::Mystring(const Mystring& p) : s_(NULL), len_(p.len_), siz_(p.siz_)
{
	s_ = new char [siz_]; //开辟空间 
	for (int i = 0; i < p.len_; i ++ ) //复制数据 
		s_[i] = p.s_[i];
}

Mystring& Mystring::operator = (const Mystring& p) //写作用域 
{
	//如果空间不够
	if (len_ < p.len_) 
	{
		delete[] s_; //释放原有的空间 
		s_ = new char[p.siz_]; //开辟新空间 
	}
	
	len_ = p.len_;
	siz_ = p.siz_;
	for (int i = 0; i < len_; i ++ )
		s_[i] = p.s_[i];
	
	return *this;
}

ostream& operator << (ostream& os, const Mystring& p) //全局函数不写作用域限定符 
{
	os << p.s_ << endl;
	return os;
}


//int main()
//{
//	Mystring str1("Hello");
//	Mystring str2(str1);
//	str1.show();
//	str2.show();
//	Mystring str3 = str1;
//	str3.show();
//	cout << str1 << endl << str2 << endl << str3 << endl;
//	return 0;
//}

Myarray.cpp

#include <bits/stdc++.h>
#include "Mystring.cpp"

using namespace std;

template<class T>
class Myarray
{
public:
	Myarray() : el_(NULL), len_(0), siz_(0) {} //无参构造 
	Myarray(int n) : el_(NULL), len_(n), siz_(2 * n) //有参构造 
	{
		el_ = new T[siz_];
	}
	~Myarray() {delete [] el_;} //析构 
	T& operator [] (int index) //重载[] 
	{
		return el_[index];
	}
	
private:
	T* el_; //数组 
	int len_; //数组长度 
	int siz_; //实际分配的长度 
};

void test01()
{
	Myarray<Mystring> a1(5);
	Mystring s("Hello");
	a1[0] = s;
	cout << a1[0] << endl;
}

int main()
{
	test01();
	
	return 0;
}