4

我是 C++ 新手,在盯着它太久之后终于放弃了尝试编译它。由于某种原因,编译器似乎拒绝了头文件中的构造函数原型......我无法弄清楚它有什么问题。

项目.h:

#ifndef ITEM_H_
#define ITEM_H_


class Item {
public:
    Item(int); //This line is what Eclipse keeps flagging up with the error in the title
    virtual ~Item();
    Item* getNextPtr();
    int getValue();
    void setNextPtr(Item *);
};

#endif /* ITEM_H_ */

在我的 Item.cpp 文件中,我有:

int val;
Item* nextPtr = 0;
Item::Item(int value) {
    val = value;
}

Item* Item::getNextPtr() {
    return nextPtr;
}

void Item::setNextPtr(Item *nextItem) {
    nextPtr = nextItem;
} 

int Item::getValue() {
    return val;
}

Item::~Item() {
    // TODO Auto-generated destructor stub
} 

糟糕,我正在使用 GCC。是的,它们应该是成员变量!我该如何使用这种格式来做到这一点?我使用实例化 Item 的代码如下。我知道其中也不应该有全局变量......

#include "LinkList.h"
#include "Item.h"

Item* first = 0;
int length = 0;

LinkList::LinkList(int values[], int size) {
    length = size;
    if (length > 0) {
        Item firstItem = new Item(values[0]);
        Item *prev = &firstItem;
        first = &firstItem;
        for (int i = 0; i < size; i++) {
            Item it = new Item(values[i]);
            prev->setNextPtr(&it);          //set 'next' pointer of previous item to current item
            prev = &it;                     // set the current item as the new previous item
        }

    }
}

LinkList::~LinkList() {
    for (int i = 0; i < length; i++) {
        Item firstItem = *first;
        Item *newFirst = firstItem.getNextPtr();
        delete(first);
        first = newFirst;
    }
}

int LinkList::pop() {
    Item firstItem = *first;
    first = firstItem.getNextPtr();
    return firstItem.getValue();
}

我刚刚注意到 pop() 和析构函数的功能存在错误...请忽略这些,我只是想弄清楚 Item 的实例化有什么问题。

海合会错误:

Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\LinkList.o" "..\\src\\LinkList.cpp" 
..\src\LinkList.cpp: In constructor 'LinkList::LinkList(int*, int)':
..\src\LinkList.cpp:16:38: error: invalid conversion from 'Item*' to 'int' [-fpermissive]
..\src\/Item.h:14:2: error:   initializing argument 1 of 'Item::Item(int)' [-fpermissive]
..\src\LinkList.cpp:20:32: error: invalid conversion from 'Item*' to 'int' [-fpermissive]
..\src\/Item.h:14:2: error:   initializing argument 1 of 'Item::Item(int)' [-fpermissive]

21:24:26 Build Finished (took 256ms)
4

1 回答 1

4

这里:

Item firstItem = new Item(values[0]);

您正在创建一个以项目指针作为参数的新项目。这与以下内容相同:

Item firstItem(new Item(values[0]));

它应该是:

Item *firstItem = new Item(values[0]);
于 2013-01-08T21:59:59.977 回答