动态创建对象 C++
Creating objects dynamically c++
好吧,我已经阅读了很多关于这个主题的不同帖子,但是 none 可以解决我的问题。
如何动态创建对象,并将它们存储在链表中。
我有这样一段代码,一个对象保存一个数字,然后它有一个指向下一个数字的指针,仅供表示。
例如:17
一个->下一个=七个。两者都是相同 class.
的对象
class Class{
private:
int value;
Class *pNext; //Points to the next object in the linked list.
public:
Class(){value = 0; }
~Class(){;}
void setV(int x){ value = x;}
int getV(){return value;}
//void setP(Class *p){ pNext = p;} ?? Is this right?
};
int main(){
Class *pFirst; //pointer to first element
Class *pLast; //pointer to last element
Class *pCurrent; //pointer to current element
for(int i = 0; i < 4;i++){
pCurrent = new Class;
pCurrent->setV(i);
//pCurrent->setP(NULL);
}
for(int i = 0; i < 4;i++){
cout << pCurrent->getV() << " ";
}
return 0;
}
谢谢
要使列表永久化,您首先必须声明您的头节点,然后对于 for 循环中的每次迭代,添加到该列表中。
int main()
{
Class *pFirst; //pointer to first element
pFirst->setV(0);
Class *pLast; //pointer to last element
Class *pCurrent; //pointer to current element
pFirst->pNext = pCurrent; // To keep track of the list via head
for(int i = 0; i < 4;i++)
{
pCurrent = new Class;
pCurrent->setV(i);
pCurrent->pNext = NULL;
}
for(int i = 0; i < 4;i++)
{
cout << pCurrent->getV() << " ";
}
return 0;
}
好吧,我已经阅读了很多关于这个主题的不同帖子,但是 none 可以解决我的问题。
如何动态创建对象,并将它们存储在链表中。
我有这样一段代码,一个对象保存一个数字,然后它有一个指向下一个数字的指针,仅供表示。 例如:17
一个->下一个=七个。两者都是相同 class.
的对象 class Class{
private:
int value;
Class *pNext; //Points to the next object in the linked list.
public:
Class(){value = 0; }
~Class(){;}
void setV(int x){ value = x;}
int getV(){return value;}
//void setP(Class *p){ pNext = p;} ?? Is this right?
};
int main(){
Class *pFirst; //pointer to first element
Class *pLast; //pointer to last element
Class *pCurrent; //pointer to current element
for(int i = 0; i < 4;i++){
pCurrent = new Class;
pCurrent->setV(i);
//pCurrent->setP(NULL);
}
for(int i = 0; i < 4;i++){
cout << pCurrent->getV() << " ";
}
return 0;
}
谢谢
要使列表永久化,您首先必须声明您的头节点,然后对于 for 循环中的每次迭代,添加到该列表中。
int main()
{
Class *pFirst; //pointer to first element
pFirst->setV(0);
Class *pLast; //pointer to last element
Class *pCurrent; //pointer to current element
pFirst->pNext = pCurrent; // To keep track of the list via head
for(int i = 0; i < 4;i++)
{
pCurrent = new Class;
pCurrent->setV(i);
pCurrent->pNext = NULL;
}
for(int i = 0; i < 4;i++)
{
cout << pCurrent->getV() << " ";
}
return 0;
}