Help With C++ CLASS Definition
I have this bit of code:
int main()
{
String s1; // s1 == ""
assert(s1.length() == 0);
String s2("hi"); // s2 == "hi"
assert(s2.length() == 2);
cout << "SUCCESS" << endl;
}
And I want to write a class that will go through it and get to the ending "cout" statement.
So far, all I have is this:
#include <iostream>
#include <cassert>
#include <string>
using namespace std;
class String
{
int size;
char * buffer;
public:
String();
String(const String &);
开发者_开发百科 String(const char *);
~String();
int length();
};
String::String()
{
buffer = 0;
}
String::String(const String &)
{
}
String::String(const char *)
{
buffer = 0;
}
String::~String()
{
delete[ ] buffer;
}
String::length()
{
}
Which I believe is correct so far, at least in terms of how a class should be built but I'm no really sure what should go within some of the member functions. Can anybody help me out or show me an example of what I need to get my class to go through the main program and compute the correct buffer size and read in the strings?
Thanks in advance.
Do you know anything about pointers and arrays?
String is basically an array of characters. What you need to do is to always allocate the right amount of memory using the new[] operator, make sure it's cleaned up when it's supposed to be (you've got it right, the delete[] operator is the correct way) and put there the content that you want.
Copy constructors should iterate through the passed char*(whether it's in the parameter or an internal char* in another String object - it's the same) and make a copy of the content.
In C++ it's common to use "null terminated strings" meaning every char* has a 0 (binary, not ASCII character 0) at the end. A function that you'll probably need is strlen - it returns the length of the string passed in the argument (by string I mean char* of course)
精彩评论