// ------------------------------------------------------------------------- // str.cpp - classe para representacao de strings. // Gabarito do TESTE PARA A PROVA PR2 // ------------------------------------------------------------------------- // Criado: 25-Out-2005 Márcio Santi // // Criado: // ------------------------------------------------------------------------- #include #include // ------------------------------------------------------------------------- // Definicao da classe String: // class String { private: int len; // tamanho da string char *s; // vetor de caracteres public: String(int); String(const char *); String(const String &); ~String(); void operator+=(const String &); friend String operator+ (const String &, const String &); friend ostream& operator<<(ostream &, const String &); friend istream& operator>>(istream &, String &); }; // ============================== operator<< =============================== // Não precisava implementar. ostream& operator<<(ostream &out, const String &t) { return(out << t.s); } // ============================== operator>> =============================== // Não precisava implementar. istream& operator>>(istream &in, String &t) { static char aux[1024]; in >> aux; delete []t.s; t.len = strlen(aux); t.s = new char[t.len + 1]; strcpy(t.s, aux); return(in); } // ================================= String ================================ String :: String(int l) { len = l; s = new char[l+1]; s[0] = 0; } // ================================= String ================================ String :: String(const char *t) { len = strlen(t); s = new char[len + 1]; strcpy(s, t); } // ================================= String ================================ String :: String(const String &t) { len = t.len; s = new char[len + 1]; strcpy(s, t.s); } // ================================ ~String ================================ String :: ~String() { delete []s; } // =============================== operator+= ============================== void String :: operator+=(const String &t) { int alen = t.len + len; char *aux = new char[alen + 1]; strcpy(aux, s); strcat(aux, t.s); delete []s; len = alen; s = aux; } // =============================== operator+ =============================== String operator+(const String &a, const String &b) { String c(a.len + b.len); strcpy(c.s, a.s); strcat(c.s, b.s); return(c); }