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

标签 c++ string

我正在做一个小程序来模拟使用基本字符串。它目前无法始终如一地工作。

在这种情况下程序工作正常:

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; .

关于c++ - 在c++中模拟基本字符串的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069180/

相关文章:

c++ - 平面方程的多面体

c++ - std::put_time 格式

c++ - 为结构类调用构造函数

c++ - 比较字符串而不分配给变量时出现问题

javascript - Node js .replace() 不是函数

javascript - 在匹配单词后使用正则表达式获取字符串?

c++ - 错误 C2955 : use of class template requires template argument list

c++ - 如何修复编译错误 "This function or variable may be unsafe"(strcpy)

java - Java 8 中的 interned 字符串是否适合垃圾回收?

c++ - QwtPlot 在 AutoScale 期间自动调整大小