我們的教授在線發佈了一個自定義的「字符串」模板文件,並要求我們前一段時間填寫下面的函數。我的問題,爲了試圖理解這一點,爲什麼前三名的構造函數有Text = NULL;
及其以下,this = source;
,它的一些其他形式。我覺得每個人都應該說Text = the_input_parameter
。爲什麼這個構造函數是這樣寫的?
非常感謝,下面的代碼:
class String
{
public:
// Default constructor
String()
{
Text = NULL;
}
String(const String& source)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = source;
}
String(const char* text)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = text;
}
~String()
{
delete[] Text;
}
// Assignment operator to perform deep copy
String& operator = (const char* text)
{
// Ddispose of old Text
delete[] Text;
// +1 accounts for NULL-terminator
int trueLength = GetLength(text) + 1;
// Dynamically allocate characters on heap
Text = new char[trueLength];
// Copy all characters from source to Text; +1 accounts for NULL-terminator
for (int i = 0; i < trueLength; i++)
Text[i] = text[i];
return *this;
}
// Returns a reference to a single character from this String
char& operator [] (int index) const
{
int length = GetLength();
// Check for valid index
if ((index < 0) || (index > length))
{
stringstream error;
error << "operator[] - index " << index << " is out of bounds (0.." << (length - 1) << ")";
throw String(error.str().c_str());
}
return Text[index];
}
private:
// The encapsulated C-string
char* Text;
};
你知道深拷貝和淺拷貝之間的區別嗎? (另外,我希望你瞭解ctor初始化列表,授權構造函數等等) – 2013-03-13 20:19:17
在純粹的褻瀆什麼邪惡的坑裏你挖出這個代碼嗎?構造函數是這樣寫的,因爲做這件事的人不知道他們在做什麼! – 2013-03-13 20:19:36
我必須同意@CrazyEddie:在賦值方面實現構造函數是屁股倒退。我曾經不得不維護一些代碼。這是酷刑。 – 2013-03-13 20:23:48