将std::basic_string赋值给字符串
Assigning a std::basic_string to a string
我的代码中有以下现有类:
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来捕获错误。
相关文章:
- 为std::string的某个索引赋值
- 将"std::string {aka std::basic_string}"赋值中的不兼容类型<char>
- std::string 的转换运算符无法处理赋值
- std::string 赋值运算符如何工作
- 如何使用 string.at 为其赋值
- Std::string 由返回 char * 的函数赋值
- QString到std::string到const char*的转换在赋值中不起作用
- 正在将std::string中的子字符串赋值为c样式字符串
- 为用soap_alloc创建的std::string指针赋值
- memset导致std::string赋值崩溃
- 赋值时执行char*,以null结束String
- 将const char*赋值给string对象有危险吗?
- 输入Std::cin与直接赋值Std::string变量不一样
- 重写std::string的赋值(=)操作符
- 错误无法在赋值中将"std::string {aka std::basic_string<char>}"转换为"char" - C++
- 当字符串超出作用域时,将string::c_str()赋值给const char*
- 如何从char *赋值std::string
- 当我将char* string赋值给std::string时,可以释放它的内存吗?
- Std::string not nothrow move可赋值或可比较
- 如何在c++中赋值string给unsigned char[]