C++操作员重载两次

C++ operator overloading, twice

本文关键字:两次 操作员 重载 C++      更新时间:2023-10-16

我正在尝试为明天的考试做一个示例考试,但我遇到了一个小问题,这可能是一个愚蠢的错误。有一个类包含一个包含 C 字符串的char*和一个包含该字符串长度的int。现在我需要让类似class[5] = 'd'的东西起作用。但我不知道怎么做。我知道我可以重载 [] 运算符以返回指向字符串特定字母的指针,但我不能直接为其分配char

我的代码:

#include <iostream>
#include <string>
using namespace std;
class DynString
{
private:
    char * _theString;
    int _charCount;
public:
    DynString(char * theString = nullptr) {
        if(theString == nullptr)
            _charCount = 0;
        else {
            _charCount = strlen(theString);
            _theString = new char[strlen(theString) + 1]; // +1 null-terminator
            strcpy(_theString, theString);
        }
    }
    char* operator[](int index) {
        return &_theString[index];
    }
    DynString operator+(const DynString& theStringTwo) {
        DynString conCat(strcat(_theString, theStringTwo._theString));
        return conCat;
    }
    void operator=(const DynString &obj) {
        _theString = obj._theString;
        _charCount = obj._charCount;
    }
    friend ostream& operator<< (ostream &stream, const DynString& theString);
    friend DynString operator+(char * ptrChar, const DynString& theString);
};
ostream& operator<<(ostream &stream, const DynString& theString)
{
    return stream << theString._theString;
}
DynString operator+(char * ptrChar, const DynString& theString) {
    char * tempStor = new char[strlen(ptrChar) + theString._charCount + 1] ;// +1 null-terminator
    strcat(tempStor, ptrChar);
    strcat(tempStor, theString._theString);
    DynString conCat(tempStor);
    return conCat;
}

int main()
{
    DynString stringA("Hello");
    DynString stringB(" Worlt");
    cout << stringA << stringB << std::endl;
    stringB[5] = 'd'; // Problem
    DynString stringC = stringA + stringB;
    std::cout << stringC << std::endl;
    DynString stringD;
    stringD = "The" + stringB + " Wide Web";
    std::cout << stringD << std::endl;
    return 0;
}

一个小演示。

#include <iostream>
#include <string.h>
using namespace std;
class String
{
private:
    char *data;
    int length;
public:
    String(const char * str)
    {
        data = new char[strlen(str)];
        strcpy(data, str);
        length = strlen(data);
    }
    char &operator[](int index)
    {
        //dont forget to check bounds
        return data[index];
    }
    int getLength() const
    {
         return length;
    }
    friend ostream & operator << (ostream &out, String &s);
};
ostream &operator << (ostream &out, String &s)
{
    for (int i = 0; i < s.getLength(); i++)
        out << s[i];
    return out;
}
int main()
{
    String string("test");
    string[1] = 'x';
    cout << string;
    return 0;
}