【问题标题】:Overriding C++ template function in derived class在派生类中覆盖 C++ 模板函数
【发布时间】:2015-01-23 07:34:46
【问题描述】:

我正在尝试编写一个在 O(1) 中返回堆栈的最小元素的堆栈,因为我正在使用派生类但没有成功。尝试从派生类调用基类的函数时出现错误。如果您可以查看代码并提供有关如何修复它的任何输入,将不胜感激。错误截图:http://imgur.com/PhoNRpq

#include<iostream>
#include<cstdlib>
#include<stack>

using namespace std;

#define MAX 999999

int findmin(int a, int b)
{
    if (a < b)
        return a;
    return b;
}
class nodeWithMin
{
public:
    int val, min;
    nodeWithMin(int x, int y)
    {
        val = x;
        min = y;
    }
};
class myStack : public stack<nodeWithMin>
{
public:
    void push(int dat) 
    {
        int newMin = findmin(dat, stackMin());
        stack<nodeWithMin>::push(new nodeWithMin(dat, newMin));
    }
    int stackMin()
    {
        if (this->empty())
            return MAX;
        else
            return this->top().min;
    }
};

【问题讨论】:

  • 请提供错误
  • 已更新错误消息。你现在可以检查一下吗?
  • 通过在此处上传 img 在 stackoverflow 上包含错误消息/图片,因为您的上传可能在某些时候变得无效。
  • 我不允许嵌入图片,因为我还没有得到 10 个代表或其他东西。所以,我编辑了这篇文章,并在截图中包含了一个超链接。又来了。 imgur.com/PhoNRpq你能帮忙吗?

标签: c++ templates stack calling-convention


【解决方案1】:

你需要改变这个:

stack<nodeWithMin>::push(new nodeWithMin(dat, newMin));

到:

stack<nodeWithMin>::push(nodeWithMin(dat, newMin));

【讨论】:

  • 其实你可以考虑把int newMin = findmin(dat, stackMin());换成newMin = dat &lt; newMin ? dat : newMin,把newMin变成myStack类的私有变量
  • 感谢您的建议。那真的会让它更紧凑:)
猜你喜欢
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2018-06-06
  • 1970-01-01
  • 2016-05-24
  • 1970-01-01
  • 2020-12-24
相关资源
最近更新 更多