>>运算符重载会出错,应该怎么改


#include
#include

using namespace std;
char* p=nullptr;

class String
{
private:
    char* pStr;
    int size;
public:
    String(const char* pn = nullptr);
    ~String();
    String(const String& S);
    void set(const char* pn);

    String operator+(const String& S);
    bool operator<(const String& S)const;
    friend ostream& operator<<(ostream& out, const String& S);
    friend istream& operator>>(istream& in, String& S);
};

String::String(const char* pn)
{
    if (pn)
    {
        pStr = new char[strlen(pn) + 1];
        strcpy_s(pStr, strlen(pn) + 1, pn);
    }
    else
    {
        pStr = new char[1];
        *pStr = '\0';
    }
    size = strlen(pStr);
}

String::~String()
{
    if(pStr)
        delete[]pStr;
}

String::String(const String& S)
{
    size = S.size;
    if (S.pStr)
    {
        pStr = new char[strlen(S.pStr) + 1];
        strcpy_s(pStr, strlen(S.pStr) + 1, S.pStr);
    }
    else
    {
        pStr = new char[1];
        *pStr = '\0';
    }
}

void String::set(const char* pn)
{
    delete[]pStr;
    pStr = new char[strlen(pn) + 1];
    strcpy_s(pStr, strlen(pn) + 1, pn);
    size = strlen(pStr);
}

String String::operator+(const String& S)
{
    if (p)
        delete[]p;
    p = new char[strlen(pStr) + strlen(S.pStr) + 1];
    strcpy_s(p, strlen(pStr)+1,pStr);
    strcat_s(p, strlen(pStr) + strlen(S.pStr) + 1, S.pStr);
    return String(p);
}

bool String::operator<(const String& S)const
{
    return (size < S.size);
}

ostream& operator<<(ostream& out, const String& S)
{
    out << S.pStr ;
    return out;
}

istream& operator>>(istream& in, String& S)
{
    in >> S.pStr;
    return in;
}

int main()
{
    String s1, s2("hello"), s3;
    cin >> s1;
    cout << s1 << endl;
    cout << s1+s2<< endl;
    if (p)
        delete[]p;
}

img

在 operator>> 函数中,输入的字符串长度可能超过 String 对象内部指针所指向的内存块的长度,从而导致内存溢出。