所以我是 c++ 的新手,抱歉,如果这不是很清楚。
我有一个类:
class Item
{
int noItem;
int qItem;
public:
Item(int noItem, int qItem)
{
this->noItem = noItem;
this->qItem = qItem;
}
int getNoItem()
{
return noItem;
}
int getQntItem()
{
return qItem;
}
};
然后是下面的类:
class Element
{
public:
Element()
{
data = NULL;
}
//to set and access data hold in node
void setElement(Item *data)
{
this->data = data;
}
Item* getElement(void)
{
return(data);
}
private:
Item *data;
};
这个还有:
class ListeChainee
{
public:
ListeChainee()
{
courant = NULL;
}
void ajoutListe(Item *data)
{
Element *newData;
//set data
newData->setElement(data);
//check if list is empty
if( courant == NULL)
{
//set current pointer
courant = newData;
}
}
//get data from element pointed at by current pointer
Item* elementCourant(void)
{
if(courant != NULL)
{
return courant->getElement();
}
else
{
return NULL;
}
}
private:
//data members
Element *courant; //pointer to current element in list
};
代码缺少一些其他东西,但我的问题是:
int main(int argc, char* argv[])
{
ListeChainee listeCH;
Item i1(123,456);
listeCH.ajoutListe(&i1);
cout << listeCH.elementCourant()->getNoItem();
system("pause");
return 0;
}
我希望输出 123,但我看到了其他数字。不知道为什么。 谢谢。
最佳答案
您的 Element *newData
没有 Element 类的实例,因此当您尝试访问 newData
指向的实例时它会崩溃。
尝试将 Element *newData;
更改为 Element *newData = new Element;
。
- ps.: 当您不再需要该实例时,不要忘记
删除
它。
关于C++指针链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26208645/