【发布时间】:2016-03-18 05:27:59
【问题描述】:
我不知道为什么我的虚函数没有被覆盖,在网上查找示例时我无法发现我做错了什么,我一定是遗漏了一些东西。
基类
class HashTable {
// removed some unrelated functions and data to keep this page short
void Insert(int key, HashTable *htable)
{
int pos = Find(key, htable);
if (htable->table[pos].info != Legitimate)
{
htable->table[pos].info = Legitimate;
int rKey = Reverse(key);
htable->table[pos].element = rKey;
}
}
virtual int Find(int key, HashTable *htable)
{
return 0;
}
};
儿童班
class SingleHash : public HashTable {
int Find(int key, HashTable *htable)
{
int hashVal = HashFunc1(key, htable->size);
while (htable->table[hashVal].info != Empty &&
htable->table[hashVal].element != key)
{
hashVal = hashVal;
hashVal = hashVal % htable->size;
prob = prob + 1;
}
trackProbes(prob);
return hashVal;
}
};
class DoubleHash : public HashTable {
int Find(int key, HashTable *htable)
{
int hashVal = HashFunc1(key, htable->size);
int stepSize = HashFunc2(key, htable->size);
while (htable->table[hashVal].info != Empty &&
htable->table[hashVal].element != key)
{
hashVal = hashVal + stepSize;
hashVal = hashVal % htable->size;
prob = prob + 1;
}
trackProbes(prob);
return hashVal;
}
};
我的主干是什么样子的
int main()
{
int value, size, pos, i = 1;
int choice = 1;
HashTable *htable = new SingleHash;
cin >> value;
htable->Insert(value, htable);
// more unrelated stuff
}
当我运行我的程序时,它只会在我调用 Insert 时返回基类 (0) 中的内容。
【问题讨论】:
-
MCVE.
-
您在 DoubleHash::Find 中缺少虚拟声明
-
看起来不错。你怎么知道派生类的函数没有被调用?你调试了吗?
-
@wizurd,虽然添加
virtual被某些人认为是良好的编程习惯,但严格来说,这不是正确性的必要条件。 -
在派生类中添加 override 关键字,然后检查错误日志,如果您的编译器接受 c++11
标签: c++ polymorphism virtual-functions