简体   繁体   English

嵌套模板化类的问题

[英]Issue with nested templated classes

I am trying to create a simple stack using templated classes. 我正在尝试使用模板化的类创建一个简单的堆栈。 There seems to be an issue when one class calls the constructor of the other class. 当一个类调用另一个类的构造函数时,似乎出现了问题。

#include <iostream>
#include <vector>


int g_MaxSize = 100;
template <class T>
class Stack;

template <class D>
class Node
{
private:
    D data;
public:
    Node(D value): data(value)
    {
    }
    template <class T>
    friend class Stack;
};

template <class T>
class Stack
{
private:
    std::vector<Node<T>> stack;
    int top;
public:
    Stack(): stack(g_MaxSize), top(0)
    {
    }

    void push(T val)
    {
        // make sure stack isnt full

        stack[top++]= Node<T>(val);
    }

    Node<T> pop()
    {
        return stack[top--];
    }

    Node<T> peek()
    {
        return stack[top];
    }
};

int  main() {

    Node<int> testNode(1) // *this works*
    Stack<int> myStack;
    myStack.push(3);

    return 0;
}

The error is " No matching constructor for initialization of 'Node' ". 错误是“没有匹配的构造器来初始化'Node'”。 As shown in the code above, Node constructor works on its own but it does not work when done through the Stack class. 如上面的代码所示,Node构造函数可以单独工作,但通过Stack类完成时则不能工作。

The argument of vector needs a default constructor. vector的参数需要默认的构造函数。 Node is missing one, hence the error. Node缺少一个,因此出错。

Your issue here is that stack(g_MaxSize) in Stack(): stack(g_MaxSize), top(0) is requesting that you construct g_MaxSize default constructed Node s in the vector. 在这里你的问题是stack(g_MaxSize)Stack(): stack(g_MaxSize), top(0)正在请求您构建g_MaxSize默认构造Node在矢量s。 You can't do that though since Node is not default constructable. 但是,由于Node无法默认构造,因此您无法执行此操作。

You can add a default constructor to Node that will fix that. 您可以向Node添加默认的构造函数来解决该问题。 Another way would be to pass a default Node to the vector constructor like stack(g_MaxSize, Node<T>(1)) . 另一种方法是将默认Node传递给矢量构造函数,例如stack(g_MaxSize, Node<T>(1)) Lastly you could create the vector with zero size and then call reserve in the constructor body to allocate the storage for the Node s without constructing them. 最后,您可以创建大小为零的向量,然后在构造函数主体中调用reserve来为Node分配存储,而无需构造它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM