// File: StringNode.cpp // // StringNode Implementation #include #include #include #include #include "StringNode.h" using namespace std ; // Constructor. We will force str not to be NULL. // StringNode::StringNode (const char *str /* = "" */ ) { if (str == NULL) { m_str = strdup("") ; // empty string has 1 char '\0' } else { m_str = strdup(str) ; } } // Destructor // Uses free() since strdup() uses malloc() // StringNode::~StringNode() { #ifndef NDEBUG cerr << " StringNode destructor\n" ; #endif assert(m_str != NULL) ; // should never be NULL free(m_str) ; } // Copy constructor // StringNode::StringNode(const StringNode& X) { assert(X.m_str != NULL) ; m_str = strdup(X.m_str) ; } // Assignment // StringNode& StringNode::operator=(const StringNode& X) { if (this == &X) return *this ; assert(m_str != NULL) ; assert(X.m_str != NULL) ; free(m_str) ; m_str = strdup(X.m_str) ; return *this ; } void StringNode::print(ostream& os /*=cout*/) const { assert(m_str != NULL) ; os << '"' << m_str << '"' ; } StringNode *StringNode::clone() const { #ifndef NDEBUG cerr << " StringNode clone\n" ; #endif return new StringNode(m_str) ; } bool StringNode::operator==(const HNode& rhs_ref) const { // comparing apples to oranges?? if (typeid(rhs_ref) != typeid(StringNode)) return false ; // This should not throw an exception, because we checked typeids // const StringNode& rhs = dynamic_cast(rhs_ref) ; assert (m_str != NULL) ; assert (rhs.m_str != NULL) ; return strcmp(m_str, rhs.m_str) == 0 ; } const char *StringNode::get() const { return m_str ; } void StringNode::set(const char *str) { if (str == NULL) { m_str = strdup("") ; } else { m_str = strdup(str) ; } }