我们的教授在线发布了一个自定义的“字符串”模板文件,并要求我们前一段时间填写下面的函数。我的问题,为了试图理解这一点,为什么前三名的构造函数有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