Rec*_*r80 0 c++ object c-strings copy-constructor default-constructor
我们的教授在网上发布了一个自定义的"String"模板文件,并在不久前问我们填写下面的功能.我的问题是,为了尝试理解这一点,这就是为什么排名前三的构造函数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;
};
Run Code Online (Sandbox Code Playgroud)
为什么不应该在赋值方面实现构造函数:
因此,在您的示例代码中以这种方式完成的原因的答案可能是您的教授不熟悉C++编程.
否则,很难说:完全没有任何意义.
然而,另一方面,即在复制构造方面实现复制分配是非常常见的,并且被称为复制和交换习语.
这很简单,例外安全且通常有效,并且如下所示:
class Foo
{
public:
void swap_with( Foo& other ) throw()
{
// No-throwing swap here.
}
void operator=( Foo other )
{
other.swap_with( *this );
}
};
Run Code Online (Sandbox Code Playgroud)
是的,就是这样.
变体包括仅命名交换器swap,并让赋值运算符返回引用,有些人更喜欢通过引用传递参数,然后复制(使用复制构造).