模拟c++中基本字符串的使用

simulate use of basic string in c++

本文关键字:字符串 c++ 模拟      更新时间:2023-10-16

我正在做一个小程序来模拟使用基本字符串。它目前工作不稳定。

在这种情况下,程序运行良好:

a = a+ w + 10 + " " + L"x" + 65.5 ; 

但如果我用这种方式写同样的句子,效果都不好:

a = + w + 10 + " " + L"x" + 65.5 ; 

有人能向我解释一下我的程序出了什么问题吗?

class sstring {
public:
    string s;
    sstring() {s.assign("");}
    template <class T>
    sstring& operator=(T i) {
        s = to_string( i );
        return *this;
    }
    sstring& operator=(const char *i) {
        s = i;
        return *this;
    }
    sstring& operator=(const wchar_t *w) {
        wstring ws = w;
        s.assign ( ws.begin(),ws.end() );
        return *this;
    }
    sstring& operator=(wstring w) {
        s.assign ( w.begin(),w.end() );
        return *this;
    }
    // *********************************************** +
    template <class T>
    sstring& operator+(T i) {
        s.append( to_string( i ));
        return *this;
    }
    sstring& operator+(const char *i) {
        s.append(i);
        return *this;
    }
    sstring& operator+(const wchar_t *i) {
        wstring ws = i;
        ws.assign(i);
        string cs;
        cs.assign ( ws.begin(),ws.end() );
        s.append( cs );
        return *this;
    }
    sstring& operator+(wstring w) {
        string temp;
        temp.assign( w.begin(),w.end() );
        s.append ( temp );
        return *this;
    }
    //*************************************************** <<
    friend ostream& operator<<( ostream &out,sstring obj);
};
ostream& operator<<( ostream &out,sstring obj) {
    out << obj.s;
    return out;
}
int main(void) {
    sstring a;
    wstring w;
    w = L"claudio";
    a = "daffra";
    a = a + w + 10 + " " + L"x" + 65.5;
    cout << "ns :" << a;
    return 1;
}

a = w + 10 + " " + L"x" + 65.5不起作用,因为w不是sstring类型,因此不会使用operator+重载。例如,尝试准备一个空的sstring:a = sstring() + w + 10 + " " + L"x" + 65.5;

这两行将给出相同的结果:

int x;
x = x + 4;
x += 4;

你建议的替代线路的形式是:

x =+ 4;

哪个被分割与相同

x = +4;

我们将其视为(尽管这可能会对类过载(:

x = 4;

如果wstring和sstring类实现了大多数人所期望的正常行为,那么这也将适用于它们。粗略地扫描一下,看起来你正试图保持这种行为

其他注释:让我们看看两个解析树。

a = a + 9 + " ";

这样做:

operator+(typeof(a), int);
operator+(typeof_previous_line, const char *);

您可能已经重载了类型+一个int和+一个const char*。

另一方面:

a += 9 + " ";

那就行了:

operator+(int, const char *);
operator+=(typeof_previous_line);

很可能您没有定义这两个操作中的第一个。常见的解决方法是将第一项强制转换为结果类型。所以类似于:

a += sstring(9) + " ";    // or
a += sstring() + 9 + " ";