//简易版string类 String
#ifndef _MYSTRING_
#define _MYSTRING_
class String
{
public:
String(const char* cstr = 0);
String(const String& str);
String& operator = (const String& str);
~String();
char* get_c_str() const { return my_data;}
private:
char* my_data;
};
};
#endif
int main()
{
String s1();
String s2("hello");
String s3(s1); //拷贝构造
s3 = s2; //拷贝复制
//简易版string类 String
#ifndef _MYSTRING_
#define _MYSTRING_
class String
{
public:
String(const char* cstr = 0); //构造函数
String(const String& str); //拷贝构造,因为它接受的是和自己一样的东西
String& operator = (const String& str); //拷贝赋值
~String(); //析构函数:在String类变量死亡时调用析构函数
char* get_c_str() const { return my_data;} //普通成员函数
private:
char* my_data;
};
};
inline
String::String(const char* cstr = 0)
{
if(cstr){
my_data = new char[strlen(cstr)+1];
strcpy(my_data, cstr);
}
else{
my_data = new char[1];
*m_data = '\0';
}
}
inline
String::~String() //构造动态分配(new)了内存,在这里必须收回内存,否则就是内存泄漏
{
delete[] m_data;
}
#endif
int main()
{
String s1();
String s2("hello");
String s3(s1); //拷贝构造
s3 = s2; //拷贝复制
class with pointer members 必须有 copy ctor(拷贝构造) 和 copy op=(拷贝赋值)
inline
String::String(const char* cstr = 0)
{
if(cstr){
m_data = new char[strlen(cstr)+1];
strcpy(m_data, cstr);
}
else{
m_data = new char[1];
*m_data = '\0';
}
}
inline
String::~String()
{
delete[] m_data;
}
ostream& operator << (ostream& os, const String& str)
{
os << str.get_c_str();
return os;
}
{
String s1("hello ");
cout << s1;
}