//实现一个自己版本的string。
#include <iostream>
#include <string.h>
using namespace std;
class String
{
public:
String(const char *s = "")
{
str = new char[strlen(s) + 1];
copy(str,s);
}
~String()
{
if (str != NULL)
{
delete[]str;
str = NULL;
}
}
String(const String &s)
{
str = new char[strlen(s.str) + 1];
copy(str,s.str);
}
String& operator=(const String &s)
{
String sp(s.str);
if (this != &s)
{
char *temp = str;
str = sp.str;
sp.str = temp;
}
return *this;
}
void Printf()
{
cout << str << endl;
}
friend istream& operator>>(istream &is,String& s)
{
char *str = new char[30];
is >> str;
String temp(str);
s = temp;
return is;
}
friend ostream& operator << (ostream &out, String& s)
{
out << s.str;
return out;
}
private:
void copy(char *dist,const char *src)
{
strcpy(dist,src);
}
private:
char *str;
};
int main()
{
String s;
cin >> s;
cout << s<<endl;
return 0;
}
#include <iostream>
using namespace std;
//实现一个简单的智能指针。
template<typename Type>
class my_auto
{
public:
my_auto(Type *p) :ptr(p)
{
count = new int[1];
count[0] = 1;
}
my_auto(const my_auto<Type>& ma)
{
ptr = ma.ptr;
count = ma.count;
count[0]++;
}
my_auto& operator=(const my_auto &ma)
{
if (this != &ma)
{
this->~my_auto();
ptr = ma.ptr;
count = ma.count;
count[0]++;
}
return *this;
}
~my_auto()
{
if (count[0]-- == 1)
{
cout << "free" << endl;
delete ptr;
ptr = NULL;
delete[]count;
count = NULL;
}
}
Type& operator*()
{
return *ptr;
}
Type* operator->()
{
return ptr;
}
private:
Type *ptr;
int *count;
};
int main()
{
my_auto<int> sp(new int(3));
my_auto<int> sb(sp);
my_auto<int> sa(new int(100));
sa = sb;
//cout << *sp << endl;
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-06 09:27:16