2014-09-30 36 views
-3

我在我的代码以下现有类:分配一个std :: basic_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_stringstring

+0

新是一个保留字 而A是一个类,而不是一个对象。 – CashCow 2014-09-30 14:15:56

+4

这就是如何做到这一点,只要这两个都是有效的对象。 'new_string'是有效的,因为你刚创建它;但我们对“A”一无所知。你是怎么创造它的,你确定它从那时起一直没有被破坏?你能发布一个完整的,可编辑的例子来演示崩溃吗? – 2014-09-30 14:18:50

+0

我知道'A.title'的内容是有效的。我可以打印'std :: string(A.title)'来验证。 – squareskittles 2014-09-30 14:51:39

回答

0

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

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

typedef basic_string<char> string; 

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

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

+0

不,'aclass.title'包含以下字符串“Sample Output”。我可以使用'std :: cout << std :: string(aclass.title);' – squareskittles 2014-09-30 15:35:51

+0

来打印它没有足够的代码来找出错误。您应该使用像gdb或ddd这样的调试器来捕获错误。像valgrind这样的内存检查工具也可以提供帮助。 – Juan 2014-09-30 15:42:27

相关问题