Łączenie tablic znaków operatorem.

0

Piszę własną klasę zastępującą std::string i muszę w jakiś sposób połączyć ze sobą dwie tablice znaków podczas dodawania do siebie String'ów. Chodzi mi o taką sytuację:

String str = "Jane has a cat.";
str = str + " And she likes it a lot!" + " Do you like Jane?";

A dokładnie o tą część:

" And she likes it a lot!" + " Do you like Jane?"

W jaki sposób mógłbym zmienić proces dodawania dwóch takich tablic podczas przypisywania ich do zmiennej typu String?

0

Nie możesz przeładować operatorów dla typów wbudowanych, to powyżej działa tylko dlatego, że jest równoważne z str = (str + " And she likes it a lot!") + " Do you like Jane?";, gdzie wynikiem wyrażenia w nawiasie jest std::string.

0

Rzecz w tym, że nie działa. Ale gdy używam std::string, to działa.

class String {
private:
    int size;
    char *buffer;
public:
    String() {
        size = 0;
        buffer = new char[size+1];
        buffer[0] = '\0';
    }
    String(const String &str) {
        size = str.size;
        buffer = new char[size+1];
        strcpy(buffer, str.buffer);
    }
    String(const char *str) {
        size = strlen(str);
        buffer = new char[size+1];
        strcpy(buffer, str);
    }

    inline String operator+(const String &str) const {
        char buf[size+str.size+1];
        strcpy(buf, buffer);
        strcat(buf, str.buffer);
        return String(buf);
    }
    inline String operator+(const char *str) const {
        char buf[size+strlen(str)+1];
        strcpy(buf, buffer);
        strcat(buf, str);
        return String(buf);
    }
    inline String &operator+=(const String &str) {
        size += str.size;
        char *buf = new char[size+1];
        strcpy(buf, buffer);
        strcat(buf, str.buffer);
        delete[] buffer;
        buffer = buf;
        return *this;
    }
    inline String &operator+=(const char *str) {
        size += strlen(str);
        char *buf = new char[size+1];
        strcpy(buf, buffer);
        strcat(buf, str);
        delete[] buffer;
        buffer = buf;
        return *this;
    }
    inline char operator[](int index) const {
        return buffer[index];
    }
    inline char &operator[](int index) {
        return buffer[index];
    }

    char *data() {
        return buffer;
    }

    ~String() {
        delete[] buffer;
    }
};
1

A gdzie masz operator przypisania i konstruktor kopiujący?

1 użytkowników online, w tym zalogowanych: 0, gości: 1