我正在用c ++写一个String类,但是当我看到一个单一的赋值操作正在调用重载的构造函数和重载的赋值运算符时,我感到困惑。 我认为在b =“ Check”行中,字符串首先转换为String对象,因此调用了重载的构造函数,然后调用了重载的赋值运算符。
String::String(const char* s)
{
cout << "Overloaded Constructor::String\n";
if (s != NULL)
{
size = strlen(s);
bufferPtr = new char[size+1];
strcpy(bufferPtr,s);
}
else
{
bufferPtr = NULL;
size = 0;
}
}
String & String::operator=(const String&rhs)
{
cout << "Operator=::String\n";
if (this != &rhs) // check same assignment
{
size = rhs.size;
delete [] bufferPtr;
if(rhs.size != 0)
{
bufferPtr = new char[rhs.size+1];
strcpy(bufferPtr,rhs.bufferPtr);
}
else bufferPtr = NULL;
}
return *this;
}
String a = "FName";
String b("LUsama");
b = "Check";
`
Output:
Overloaded Constructor::String
Overloaded Constructor::String
Overloaded Constructor::String
Operator=::String
答案 0 :(得分:0)
好吧,让我们看看...
a
构造函数b
构造函数b
正如输出所示。是什么让您感到困惑?