【问题标题】:I have a C++ function that compiles in Dev C++ but not in G++我有一个在 Dev C++ 中编译但不在 G++ 中编译的 C++ 函数
【发布时间】:2017-09-01 05:25:30
【问题描述】:

我的主函数调用链表中的删除函数

 case 7:
    input >> argument;
    cout << "Attempting to remove " << argument << endl;
    if(myList.remove(argument))
    {
        cout << "Successfully removed the element from the list\n";
    }
    else
    {
        cout << "Could not remove the element from the list\n";
    }
    break;

我的结构和函数调用看起来像这样

#ifndef LL_H
#define LL_H

// include this library to use NULL, otherwise use nullptr instead
#include <cstddef>

// include iostream so anything that includes this file can use cout
#include <iostream>

// Struct which will be the building block of our list
struct node{
    int val;
    node* next;
    node* prev;
};

// Linked list class definition
class LL{
public:
    LL();
    void prepend(int);
    void append(int);
    void remove(int);
    bool removeFront();
    bool removeBack();
    node* search(int);
    void print();
    void deleteList();
private:
    node* head;
};

#endif

mycpp 文件看起来像这样

    #include "ll.h"
    LL::LL()
    {
        head = NULL;
    }
    void LL::remove(int num){

该函数搜索以num为值的节点,如果找到则从列表中删除

        node* second = head;
        node* first = head->next;
        if (head == NULL)
        {
            return;
        }
        else if (head->val == num)
        {
            node* temp = head;
            head = head->next;
            delete temp;
        }   


        while (first&&first->val != num)
        {
            second = first;
            first = first->next;
        }
        if (first)
        {
            second->next = first->next;
            delete first;
        }

    }

错误是无法将 myList remove 参数从 void 转换为 BOOL 但我在说什么认为 BOOL 函数?我不会传回 truefalse 值。

【问题讨论】:

  • 确切的错误信息是什么,它指向哪一行?
  • 在函数'int main()'中:main.cpp:66:29:错误:无法将'myList.LL::remove(argument)'从'void'转换为'bool'如果(mylist.remove(argument))
  • 说真的,您有一个使用 C++ 编译器的 C++ 程序,并且您认为选择的最佳语言标签是 C - 并且只有 C?
  • 它被标记在 C++ 和链表中

标签: c++ linked-list


【解决方案1】:

问题在于remove 被声明为void 函数,并且它没有返回值。所以你不能在if() 语句中使用它,因为它不会返回一个可以转换为布尔值并经过测试的值。

去掉if()周围的myList.remove(argument)调用:

case 7:
    input >> argument;
    cout << "Attempting to remove " << argument << endl;
    myList.remove(argument);
    break;

由于函数没有返回值,所以无法报告是否成功。如果你真的需要这样做,你必须改变函数的定义,让它返回一个布尔值。

【讨论】:

  • 天啊,我发现如果语句那么 G++ 真的炸毁了 main.cpp 对 LL 的未定义引用:LL() main.cpp 对 LL 的未定义引用:prepend(int)' main.cpp 未定义引用到 LL:append(int)' 等.....
  • @KristoferBeck 不要通过引入另一个问题来解决问题。询问那个而不是你尝试的解决方案。
  • @KristoferBeck 除了删除呼叫周围的if 之外,您一定做了其他事情。我已经编辑了答案以显示它应该是什么样子。
猜你喜欢
  • 2016-06-22
  • 1970-01-01
  • 1970-01-01
  • 2011-10-08
  • 1970-01-01
  • 2011-01-10
  • 2013-05-03
  • 2012-08-06
  • 2015-05-31
相关资源
最近更新 更多