// LearnSTL.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <queue>
#include <ctime>
#include <cstdlib>
using namespace std;
//细胞分裂模拟
const int SPLIT_TIME_MIN = 500;
const int SPLIT_TIME_MAX = 2000;
class Cell;
priority_queue<Cell> cellQueue;
class Cell
{
private:
static int count;//细胞总数
int id;//当前细胞编号
int time; //细胞分裂时间
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& s) const//定义 "<"
{
return time >s.time;
}
void split()
{
Cell child1(time), child2(time);//建立两个子细胞
cout << time << "s:Cell #" << id << " split to #"
<< child1.getId() << " and #" << child2.getId() << endl;
cellQueue.push(child1);//将第一个子细胞压入优先级队列
cellQueue.push(child2);//将第二个子细胞压入优先级队列
}
};
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();//模拟下一个细胞的分裂,//error C2662
cellQueue.pop();
}
return 0;
}
严重性 代码 说明 项目 文件 行 禁止显示状态错误 C2662 “void Cell::split(void)”: 不能将“this”指针从“const Cell”转换为“Cell &” LearnSTL c:\users\simon\source\repos\learnstl\learnstl\learnstl.cpp 57
原因:

图1, top() 的原型
因为 cellQueue.top() 返回的是 const Cell& ,是一个const对象的引用,所以只能调用被声明为const的成员函数 。解决办法:将 void split() 改成 void split () const
参考:https://blog.youkuaiyun.com/lihao21/article/details/8634876
参考:https://blog.youkuaiyun.com/lihao21/article/details/8634876
“在C++中,只有被声明为const的成员函数才能被一个const类对象调用。”