#include <string.h>
using namespace std;
class String
{
public:
String(const char *str = NULL); // 通用構造函數
String(const String &another); // 拷貝構造函數
String & operator=(const String &rhs); // 賦值函數
~ String(); // 析構函數
char *m_data; // 用於保存字符串
};
String::String(const char *str)
if ( str == NULL ) //strlen在參數爲NULL時會拋異常纔會有這步判斷
{
m_data = new char[1] ;
m_data[0] = '\0' ;
}
else
{
m_data = new char[strlen(str) + 1];
strcpy(m_data,str);
}
{
m_data = new char[strlen(another.m_data) + 1];
strcpy(m_data,another.m_data);
}
if ( this == &rhs)
return *this ;
delete []m_data; //刪除原來的數據,新開一塊內存
m_data = new char[strlen(rhs.m_data) + 1];
strcpy(m_data,rhs.m_data);
return *this ;
}
delete []m_data ;
}
{
String s1 = "hello world"; //只調用String(const char *str)
String s2 = s1; //這裏只會調用拷貝 而不會調用重載等於。
s2 = s1; //只調用重載等於
s2 = "sddsf"; // **這個地方是重點 先把會這個字符數組 隱轉換爲const char *,然後調用構造函數- String(const char *str),再調用重載等於
return 0;
}