Daily Archive for August 9th, 2009

Simple C++ String Class

Every C++ programmer knows that the standard library has a string class. But, while learning, it’s a good idea to know how to develop your own string class.

That’s why I made the String class. It’s not intended for professional projects (for them, you should use the standard library’s string), but as help to learn C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class String
{
    char *m_pszString;  //Allocated buffer
    int m_nAllocated;   //Allocated length
 
public:
    //Construction and destruction
    String() { /* ... */ }
    ~String() { /* ... */ }
 
    //Copy constructors
    String(const char *pszString) { /* ... */ }
    String(const String& rsString) { /* ... */ }
 
    //Operators (assignment)
    String& operator=(const char *pszString);
    String& operator=(const String& rsString) { /* ... */ }
 
    //Operators (concatenation)
    String& operator+=(const char *pszString);
    String& operator+=(String& rsString) { /* ... */ }
    String operator+(String rsString);
 
    //Operators (comparison)
    bool operator<(String sString) { /* ... */ }
    bool operator<=(String sString) { /* ... */ }
 
    bool operator>(String sString) { /* ... */ }
    bool operator>=(String sString) { /* ... */ }
 
    bool operator==(String sString) { /* ... */ }
    bool operator!=(String sString) { /* ... */ }
 
    //Operations
    void Clear();
    String Lower() { /* ... */ }
    String Upper() { /* ... */ }
 
    //Information
    int Length() { /* ... */ }
 
    //Cast operators
    operator const char*() { /* ... */ }
 
protected//Helper functions
    /* ... */
};
 
//Output e input
std::ostream& operator<<(std::ostream& oStream, String& rsString);
std::istream& operator>>(std::istream& iStream, String& rsString);

Keep reading…

Incoming search terms for the article: