I am writing a class of String in c++ but I got confused when I saw that overloaded constructor and overloaded assignment operators were being called by a single assignment operation. I am thinking that in b = "Check" line, string is first converted into String object hence overloaded constructor was called, then overloaded assignment operator was called.
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
Well, let's see...
a
constructor b
constructor b
via operator Just as the output shows. What confuses you?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.