细胞分裂模拟(C++)
一种细胞在诞生(即上次分裂)后会在 500 ~ 2000 秒内分裂为两个细胞,每个细胞又按照同样的规律继续分裂。下面的程序模拟了细胞分裂的过程,会输出每个细胞的分裂时间。代码如下:
//==========================================
// Filename : 细胞分裂模拟
// Time : 2019年5月1日
// Authonr : 柚子树
// Email : [email protected]
//==========================================
#include <iostream>
#include <string>
#include <cmath>
#include <queue>
#include <cstdlib>
#include <ctime>
using namespace std;
const int SPLIT_TIME_MIN = 500; // 细胞分裂最短时间
const int SPLIT_TIME_MAX = 2000; // 细胞分裂最长时间
class Cell;
priority_queue <Cell> cellQueue;
class Cell // 细胞类
{
public:
Cell(int birth) : id(count++) // birth 为细胞诞生时间
{
time = birth + (rand() % (SPLIT_TIME_MAX - SPLIT_TIME_MIN)) + SPLIT_TIME_MIN;
}
int getId() const { return id; } // 获取细胞编号
int getSplitTime() const { return time; } // 获取细胞发生分裂时间
bool operator<(const Cell &c) const
{
return time > c.time;
}
// 细胞分裂
void split() // 如果不加 const 程序会报错
{
Cell child1(time), child2(time); // 建立两个子细胞
cout << time << "s: Cell #" << id << " splits to #"
<< child1.getId() << " and #" << child2.getId() << endl;
cellQueue.push(child1); // 第一个子细胞压入优先级队列
cellQueue.push(child2); // 第二个子细胞压入优先级队列
}
private:
static int count; // 细胞总数
int id; // 细胞编号
int time; // 细胞分裂时间
};
int Cell::count = 0;
int main()
{
srand(static_cast<unsigned>(time(0)));
int t; // 模拟时间长度
cout << "Simulation time: ";
cin >> t;
cellQueue.push(Cell(0)); // 将第一个细胞压入优先级队列
while (cellQueue.top().getSplitTime() <= t)
{
cellQueue.top().split(); // 模拟下一个细胞的分裂
cellQueue.pop(); // 将刚刚分裂的细胞弹出
}
system("pause");
return EXIT_SUCCESS;
}
进行编译发现:error C2662: “void Cell::split(void)”: 不能将“this”指针从“const Cell”转换为“Cell &”
出错代码行:cellQueue.top().split(); // 模拟下一个细胞的分裂
经过排查得知,STL 中的很多函数都是 const 限定的,top() 函数也是被 const 修饰的,C++ 在调用类的成员函数时会隐式传递 this 指针,相当于:cellQueue.top(const Cell *this).split(const Cell *this);
在调用 split() 函数时,也会将这个参数传进去,但是 split() 函数没有被 const 修饰,发生了类型不匹配问题,所以需要将 split() 函数也用 const 修饰。
修改后运行结果: