【问题标题】:Assigning a std::basic_string to a string将 std::basic_string 分配给字符串
【发布时间】:2014-09-30 14:14:22
【问题描述】:

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

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 是否需要进行一些转换?

【问题讨论】:

  • new 是保留字,A 是类而不是对象。
  • 就是这样,只要两者都是有效的对象。 new_string 是有效的,因为您刚刚创建了它;但我们对A 一无所知。你是如何创造它的,你确定它从那时起就没有被摧毁吗?您能否发布一个完整的、可编译的示例来演示崩溃?
  • 我知道A.title的内容是有效的。我可以打印std::string(A.title)来验证。
  • 只是您给出的代码无法编译; new_string = A.title; 行抱怨我不能在类型名称(或类似名称)之后使用 .。真正的代码是什么?
  • @squareskittles 你能打印new_stringtypeid吗?

标签: c++ string casting stdstring


【解决方案1】:

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

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

typedef basic_string<char> string;

这是一个 char 类型的 basic_string 的模板实例化。如果只在代码中引用 std::string,则无需转换。

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

【讨论】:

  • 不,aclass.title 包含以下字符串“样本输出”。我可以使用std::cout &lt;&lt; std::string(aclass.title); 打印它
  • 没有足够的代码来找出问题所在。您应该使用 gdb 或 ddd 之类的调试器来捕获错误。像 valgrind 这样的内存检查工具也可以提供帮助。
猜你喜欢
  • 2020-04-23
  • 1970-01-01
  • 2015-07-11
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
相关资源
最近更新 更多