gpt4 book ai didi

c++ - 在 C++ 中重新分配堆栈上的对象

转载 作者:行者123 更新时间:2023-11-28 02:36:56 26 4
gpt4 key购买 nike

我来自 Java,发现某些对象非常困惑。

在我的代码中,我有一个具有 Cell 属性的事件类。当我创建一个新事件时,我想在不使用“new”关键字的情况下初始化单元格。代码如下。在 Event 的构造函数中,我能想到的就是放置“currentCell = new Cell()”。有没有什么方法可以在不这样做的情况下初始化 currentCell?

更一般地说,如果我有一个像 currentEvent 这样的对象,我怎样才能刷新它以获得不同的信息?假设 currentEvent 有单元格 a 和时间点 10,现在我希望它存储单元格 b 和时间点 12。在 java 中我会这样做:

Event e1 = new Event(a, 10);
e1 = new Event(b, 12);

但我想在 c++ 中做同样的事情而不把任何东西放在堆栈上。

这是事件头文件:

class Event {
public:
Event();
int getTime() { return timePoint; }
void setTime(int newTime);
void setCell(Cell & newCell);
virtual ~Event();
private:
Cell * currentCell; //Class is made up of a pointer to a cell and a time
int timePoint;
};

以及Event.cpp中的构造函数:

Event::Event()
{
//Cell currentCell;
currentCell = new Cell(); //don't want to use new, but do what to initialize currentCell to a blank new cell
timePoint = rand() % 6 + 5;
}

一般问题:

priority_queue<Event, vector<Event>, CompareEvent> events;
Event firstEvent(*start, time);
events.push(firstEvent);
Event * newEvent1; //I want to reassign newEvent1 and newEvent2 each time through the loop but would rather not have to use the heap
Event * newEvent2;

//temp int counter
int counter = 0;

while ((!(events.empty())) && (counter<5000)){

//Get next event
currentEvent = events.top();
currentCell = currentEvent.getCell();
if (currentCell->isAlive()) {

bool canGrow = false;
if (currentCell->selfGrows() || currentCell->withinRange()){
canGrow = true;
}

if (canGrow){

//Perform mitosis

//Create a daughter cell and add it to the list; increment counter
daughterCell = new Cell(*currentCell);

newEvent1 = new Event(*daughterCell, time, newDir);
events.push(*newEvent1);

}

}
}

最佳答案

没有指向 Cell 的指针,只有一个成员 Cell。它将在构造包含 Event 对象的过程中构造。

class Event {
public:
Event();
int getTime() { return timePoint; }
void setTime(int newTime);
void setCell(Cell & newCell);
virtual ~Event();
private:
Cell currentCell; // <-- no need to have this as a pointer (asterisk removed)
int timePoint;
};

关于c++ - 在 C++ 中重新分配堆栈上的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27130749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com