主要講帶指針的類設(shè)計
目標(biāo):
String s1();? //默認(rèn)構(gòu)造
String s2("hello");? // 字符串構(gòu)造
String s3(s1); // 拷貝構(gòu)造
cout << s3 << endl;? //輸出
s3 = s2;? //賦值函數(shù)
cout << s3 << endl;
inline
String::String(const char* cstr = 0)
{
if(cstr)
{
m_data = new char[strlen(cstr)+1];? // +1相當(dāng)于結(jié)束符
strcpy(m_data , cstr);
}
else //未指定初值的話 只放一個\0
{
m_data = new char[1];
*m_data = '\0';
}
}
inline
String::~String()
{
delete[] m_data;? // 把數(shù)組從內(nèi)存中清除掉
}
使用
String s1();
String s2("hello");
String * p = new String("hello");
delete p;
還帶我們看了編譯Debug版本時類在內(nèi)存中實際分配的方式
new數(shù)組 注意與delete[] 相互搭配
還有很多細(xì)節(jié)沒有講 需要自己去研究