I know for some C++ experts this class overload is like a piece of cake but as a beginner we always asked to write this again and again.
My code as following don't have compiler problem but have strange output.
Class String
{
public:
String (const String& s);
String& append(const String& other);
private:
void init();
void ensureSize(size_t size);
char* m_buffer;
size_t m_length;
size_t m_bufSize;
}
//constructor
String::String(char *s)
{
init();
append(s);
}
//implement append() function inside the constructor
String& String::append(const char *other)
{
size_t newlen=strlen(other);
ensureSize(newlen+m_length+1);
int i=0;
for(i;i<newlen;++i)
{
m_buffer[i+m_length]=other[i];
}
m_length=newlen+m_length;
return *this;
}
//implement init() inside constructor(this one i couldn't change)
void String::init()
{
m_buffer = NULL;
m_length = 0;
m_bufSize = 0;
}
//overload <<(this one i couldn't change)
ostream& operator<< (ostream& os, const String& s)
{
String temp = s;
// Add null terminator so we can use ostream's char* output operator
temp.ensureSize(temp.m_length + 1);
temp.m_buffer[temp.m_length] = 0;
os << "S(" << temp.m_length << "," << temp.m_bufSize
<< ")[" << temp.m_buffer << "]";
return os;
}
Here is my driver:
int main()
{
String ditty ("Are you sleeping?\n");
cout<<ditty;
}
The attachment is my strange output.
I have no idea where is my bug??
Thanks.