简体   繁体   中英

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' ". As shown in the code above, Node constructor works on its own but it does not work when done through the Stack class.

The argument of vector needs a default constructor. Node is missing one, hence the error.

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. You can't do that though since Node is not default constructable.

You can add a default constructor to Node that will fix that. Another way would be to pass a default Node to the vector constructor like 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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