【发布时间】: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_string和typeid吗?
标签: c++ string casting stdstring