![](/img/trans.png)
[英]Error cannot convert 'std::string {aka std::basic_string<char>}' to 'char' in assignment - C++
[英]Why am I getting error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘char*’ in assignment?
我無法讓這個程序正確編譯。 它適用於一個單向鏈表的程序。 這個特殊的函數讓我沒有將其中的內容轉換為字符串,但我看不到它。 有人告訴我要解決這個函數必須接受字符串而不是 char* 的另一個問題,我得到了幫助。 我以為我修復了與用字符串替換 char* 相關的所有錯誤,但我似乎無法修復最后一個。 請幫幫我! 這是問題函數:
List_Node *listTextEditor::create_node(string value)//creates the list elements
{
struct List_Node *tempNode, *s;
tempNode = new(struct List_Node);
if (tempNode == NULL)
{
cout << "Memory not allocated " << endl;//if theres nothing in the list
return 0;
}
else
{
tempNode->textLine=value ; //This puts stuff in the current node and creates/moves to the next. THIS IS WHERE THE PROBLEM IS!!!!!!!!!
tempNode->nextEle = NULL;
return tempNode;
}
}
根據我假設的錯誤消息,您的List_Node
類的定義有點像這樣:
struct List_Node {
char* textLine;
List_Node* nextEle;
};
您不能將std::string
分配給char*
(后者是 C 風格的字符串,需要手動內存管理)。 由於您使用的是 C++,因此請堅持使用它的字符串類std::string
。
改為將您的類定義更改為:
struct List_Node {
std::string textLine;
List_Node* nextEle;
};
List_Node *listTextEditor::create_node(string value) { return new ListNode{value, nullptr}; }
如果您提供了List_Node
的定義,那將會很有幫助。 我將假設以下內容。
struct List_Node {
char *textLine;
List_Node *nextEle;
};
現在, char *
類型只是指向某些char
數據的指針。 它實際上並沒有為該數據分配任何內存。您不能將std::string
值分配給char *
變量,因為除非您分配內存,否則char *
沒有任何地方可以存儲字符串. (然后即使您分配了足夠的內存來保存字符串,您仍然需要進行字符串復制而不是簡單的賦值,因為您想要復制底層字符串數據,而不僅僅是更改指針地址。)意味着您要么需要自己分配內存,並在完成后將其刪除,要么使用像std::string
這樣的類型,它在內部進行自己的內存分配。
對於前者,你會做這樣的事情,並且在刪除列表節點時有義務delete[] textLine
。
{
tempNode->textLine = new char[value.length()+1];
strcpy(tempNode->textLine, value.c_str());
tempNode->nextEle = NULL;
return tempNode;
}
對於后者,您只需更改List_Node
的定義。
struct List_Node {
std::string textLine;
List_Node *nextEle;
};
一個不相關的問題是new
在無法分配內存時不會返回NULL
。 它拋出一個bad_alloc
異常。 因此,如果您想檢查分配是否成功,您實際上需要將它放在 try-catch 塊中,或者使用new (std::nothrow) List_Node
指示它在失敗時返回 NULL 而不是拋出異常. 或者您可以忽略故障並允許內存分配失敗的情況導致未處理的異常並終止程序執行,因為無論如何您可能無法從內存不足的系統中恢復,並且考慮到簡單性如果您有一個不斷分配內存的無限循環,則只有您的程序才有可能遇到此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.