// CSE 374 String example #ifndef STRING_374_H #define STRING_374_H #include namespace cse374 { /** * Our String represents a wrapped raw C string with additional operations, as * a demonstration of concepts; in reality you would almost always use * std::string. */ class String { public: // Zero-argument constructor makes an empty string. String(); // "Copy constructor" - creates a new String from a copy of the parameter. String(const String& other); // Create a String from a raw char array. // A single-argument constructor that is not a copy constructor is called a // "converting constructor", which means C++ will use it for you to convert // between the argument type and the class type. You can do things like this: // cse374::String s = "foo"; // We didn't call the constructor directly! Instead, C++ saw that we were // trying to do a "conversion" and called the converting constructor for us. // If you DON'T want this automatic conversion behavior, we can add "explicit" // to the constructor, which requires any constructor calls to be explicit: // explicit String(const char* raw); // Throws a std::runtime_error if the passed char* is NULL. String(const char* raw); // Destructor - when the String is deleted (heap) or goes out of scope // (stack), the destructor will automatically be called to help clean up any // fields that should be cleaned up (in this case, the char* raw string on the // heap). // Destructors should almost always be "virtual", which we will discuss later. virtual ~String(); // Assignment operator - this deletes all of the internal data and replaces it // with a copy of the data in the String passed as a parameter. String& operator=(const String& other); // Member function - returns the length of the String. size_t length() const; // Member function - adds a copy of the given String to the end of this // String. void append(const String& other); // Member function - deletes all of the contents of this string. void clear(); // This allows us to print the String directly to an ostream! We can do: // std::cout << s << std::endl; // This is NOT a member function of String! It is a global function that we // are OVERRIDING with behavior for String (allowing it to understand the // String). We use the keyword "friend" on the front, which will allow the // operator to access the otherwise-private internal state of String (ie the // raw char*). friend std::ostream& operator<<(std::ostream& out, const String& s); private: // Helper function that stores a new char* array of the given length (plus an // additional one, for the null-terminator) on the heap in the raw_ field. void makeNewRaw(size_t length); // Raw C string stored on the heap. char* raw_; }; } #endif