My project asks to implement a string class in C++, however, I'm confused about one of the public function
class String
{
private:
char* buffer;
int size;
public:
// Initializes a string to be empty (i.e., its length will
// be zero and toChars() will return "").
String();
// Initializes a string to contain the characters in the
// given C-style string, which is assumed to be null-terminated.
String(const char* chars);
// Initializes a string to be a copy of an existing string,
// meaning that it contains the same characters and has the
// same length.
String(const String& s);
// Destroys a string, releasing any memory that is being
// managed by this object.
~String() noexcept;
};
Besides String(const char* chars);
function, I implemented all of them correctly, but I don't have any clues about how to implement this one.
Edited:
Since c++ standard library cannot be used, I have to compute the size of chars
by not using strlen()
String::String(){
size = 0;
buffer = nullptr;
}
String::String(const char* chars){
int i = 0;
for (char* p = chars;*p != '\0'; p++){
++i;
}
size = i;
buffer = new char[size+1];
i = 0;
for(;i<size;i++){
buffer[i] = chars[i];
}
buffer[i] = '\0';
}
String::String(const String& s){
size = s.size;
buffer = new char[size];
for int(i=0;i<size;i++){
buffer[i] = s.buffer[i];
}
}
String::~String() noexcept{
delete[] buffer;
}