2014-09-30 34 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

相關問題