将std::basic_string赋值给字符串

Assigning a std::basic_string to a string

本文关键字:赋值 string 字符串 std basic      更新时间:2023-10-16

我的代码中有以下现有类:

struct Aclass {
    typedef std::string TitleType;
    TitleType title;
    typedef std::size_t NumType;
    NumType some_num;
};

在实例化了Aclass,比方说aclass之后,我在程序中将aclass.title设置为某个字符串。在另一个功能中,我想做以下操作:

NumType new_num;
std::string new_string;
new_num = aclass.some_num;  // this works, verified by print statement
new_string = aclass.title;  // this doesn't work

typeid(aclass.title)按预期提供了basic_string类型,但分配给new_string导致我的程序崩溃。我怎样才能正确地完成这项作业?从basic_string转换回string是否需要一些转换?

是否将.title设置为NULL或0,而不是"。当您尝试分配字符串时,这将导致崩溃。

字符串是(请参见http://www.cplusplus.com/reference/string/string/):

typedef basic_string<char> string;

其是具有char类型的basic_ string的模板实例化。如果在代码中只引用std::string,则不需要进行转换。

除此之外,我建议使用调试器,如gdb或ddd来捕获错误。