【发布时间】:2009-10-14 17:57:11
【问题描述】:
我正在创建一个从 STL 库继承队列的新类。该类的唯一添加是向量。该向量将具有与队列相同的大小,并将存储一些整数值,这些值将对应于队列中的每个对象。
现在,我想重写 pop() 和 push(),但我只是想为父类的方法添加更多功能。
例如。当对队列对象调用 pop() 时,我还想从向量中弹出一个对象。当对队列对象调用 push() 时,我还想在向量中插入一个新对象。
我该怎么做???
#include <iostream>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
template <typename type>
class CPU_Q : public queue<type>
{
public:
vector<int> CPU_TIME;
void increaseTime()
{
for(int ndx = 0; ndx < CPU_TIME.size(); ndx++)
{
CPU_TIME[ndx]++;
}
}
void push(type insertMe)
{
//This is what I want to do
super::push(); // or queue::push(); maybe?
CPU_TIME.push_back(0);
}
void pop()
{
//Something very similar to push()
}
}
非常感谢提前
-三
【问题讨论】:
-
C++ 没有
super关键字的原因可能是C++ 中有多重继承。你可以有几个基类/超类。所以你改用基类的正确类型:queue<type>::push(insertMe)。但是,请确保您阅读了解释为什么从 STL 容器继承可能不是您想要的答案。 -
您是否也考虑过简单地将这些值放入自己的结构中,这样您就可以始终保证相关值一起添加和删除?
标签: c++ inheritance