【问题标题】:Why am I getting error: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘char*’ in assignment?为什么我收到错误:无法在赋值中将“std::string {aka std::basic_string<char>}”转换为“char*”?
【发布时间】:2017-02-12 00:02:00
【问题描述】:

我无法让这个程序正确编译。它适用于一个单链表的程序。这个特殊的功能让我很讨厌没有将其中的内容转换为字符串,但我看不到它。我得到了某人的帮助,他告诉我要解决另一个问题,这个函数必须接受字符串而不是 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;
        }
}

【问题讨论】:

  • textLine是字符串类成员数据吗?
  • 没有从std::string 到(可变)char* 的隐式转换。另外,与您的问题无关:if (tempNode == NULL) 永远无法评估为true。看看operator new 做了什么。
  • 添加类接口示例
  • 错误信息没有告诉你吗?您正在尝试将 std::string 转换为 char*,但您不能。

标签: c++ function linked-list char


【解决方案1】:

根据我假设的错误消息,您的 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};
}

【讨论】:

    【解决方案2】:

    如果您提供了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 而不是抛出异常。或者您可以忽略故障并允许内存分配失败的情况导致未处理的异常并终止程序执行,因为您可能无法从内存不足的系统中恢复,并且考虑到简单性如果你有一个不断分配内存的无限循环,你的程序只有可能会遇到这个问题。

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 2014-07-13
      • 2021-10-28
      • 2023-03-21
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      相关资源
      最近更新 更多