细胞分裂模拟(C++)

一种细胞在诞生(即上次分裂)后会在 500 ~ 2000 秒内分裂为两个细胞,每个细胞又按照同样的规律继续分裂。下面的程序模拟了细胞分裂的过程,会输出每个细胞的分裂时间。代码如下:
#include
#include
#include
#include
#include
#include
using namespace std;

const int SPLIT_TIME_MIN = 500; // 细胞分裂最短时间
const int SPLIT_TIME_MAX = 2000; // 细胞分裂最长时间

class Cell;
priority_queue 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(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 修饰。
修改后运行结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值