我正在为一个类实现一个页面替换算法,我在比较其中一个算法的内部类时遇到了问题,其中我的泛型Frames
类(类似于vector,但是大小固定了)它没有调用我重载的==
运算符。
在Algo.cpp
中,我有一句话:
const bool contains = this->frames->contains(new scNode(data));
从我的contains
类调用Frames
方法:
bool contains(T data) {
for(unsigned i = 0; i < this->_size; i++) {
if(this->list[i] == data) { // not calling scNode == operator
return true;
}
}
return false;
}
我遇到的问题是==
方法中没有调用Algo::scNode
中定义的重载contains
运算符。我尝试使用访问修饰符,但没有骰子。有人能指出我正确的方向吗?
Algo.h
#include "Page.h"
#include "Frames.h"
class Algo {
public:
static Algo* get();
void run(Page page);
unsigned faults();
class scNode {
public:
unsigned reference:1;
int data;
unsigned long _time;
scNode(int data) {
this->data = data;
this->reference = 0;
this->_time = (unsigned long) time(NULL);
}
bool operator==(const scNode &other) {
return this->data == other.data;
}
};
private:
static Algo* instance;
Algo() {
this->_faults = 0;
}
unsigned _faults;
Page page;
Frames<scNode*> *frames;
/**
* @return the index to remove from the Frame object.
*/
int removeIndex();
};
Algo.cpp
#include <ctime>
#include <iostream>
#include "SecondChance.h"
SecondChance* SecondChance::instance = NULL;
SecondChance* SecondChance::get() {
if(instance == NULL) {
instance = new SecondChance();
}
return instance;
}
void SecondChance::run(Page page) {
this->page = page;
this->frames = new Frames<scNode*>(this->page.frames, NULL);
unsigned index = 0;
for(unsigned i = 0; i < this->page.pages.size(); i++) {
const int data = this->page.pages[i];
const bool contains = this->frames->contains(new scNode(data));
scNode *node = this->frames->get(index);
if(node == NULL && !contains) { // entry is empty
std::cout << "Fault: " << data << "\r\n";
SecondChance::_faults++;
this->frames->add(new scNode(data));
if(++index == 3) {
index = 0;
}
} else if(contains) {
if(node != NULL) {
~node->reference;
node->_time = (unsigned long) time(NULL);
} else {
throw new std::runtime_error("Bad reference to node");
}
}
}
delete this->frames;
}
unsigned SecondChance::faults() {
return this->_faults;
}
int SecondChance::removeIndex() {
unsigned long min = ULONG_MAX;
int minIndex = 0;
unsigned total1s = 0;
for(int i = 0; i < this->frames->size(); i++) {
scNode *node = this->frames->get(i);
if(node->_time < min) {
min = node->_time;
if(node->reference == 0) {
minIndex = i;
}
}
if(node->reference == 1) {
~node->reference;
total1s++;
}
}
if(total1s == this->frames->size()) {
min = ULONG_MAX;
for(int i = 0; i < this->frames->size(); i++) {
scNode *node = this->frames->get(i);
if(node->_time < min) {
min = node->_time;
minIndex = i;
}
}
}
return minIndex;
}
答案 0 :(得分:1)
你正在比较两个指针。您需要比较它们的值。
答案 1 :(得分:1)
问题在于以下说明:
this->frames = new Frames<scNode*>(this->page.frames, NULL);
所以对于Frames<T>
T是scNode *,但我相信你打算只使用scNode。目前你比较两个指针,但如果你使用Frames<scNode>
,那么将为scNode调用重载的operator ==
。