My struct type is not recognized within my class

Asked

Viewed 68 times

0

Guys, I’m implementing a stack with C++ pointers and have the following code for now:

template <class T>
struct Node {
    T item;
    Node *prox;
};

class Pilha {
    private:
    int tamanho;
    Node *topo;

    public:
    Pilha() {
    this->topo=NULL;
    this->tamanho=0;    
}

In the private attribute top, the guy Node is not being recognized within my class Stack. The eclipse returns the following error: Type 'Node' could not be resolved.

What can it be? Thank you!

1 answer

1


The problem is that its structure Node has a template, which will be used to create a Node of any kind, so you must also use this pattern in the class Pilha for the compiler to know what type of Node may vary:

template <class T>
struct Node {
    T item;
    Node *prox;
};

template <class T> // indicação que esta classe tambem usa template
class Pilha {
private:
    int tamanho;
    Node<T> *topo; //aqui o Node é indicado com <T> 

public:
    Pilha() {
        this->topo=NULL;
        this->tamanho=0;
    }
};

In the code above, I only commented on the places I changed.

Note that when instantiating a node you have to use the template notation. Example:

Node<T> *novoNo = new Node<T>();

In c++ also has a better alternative to NULL that is nullptr and which is a pointer literal and avoids some implicit conversions that in certain situations generate problems.

  • I have to put the <T> in the *Node top , both in struct qnt in private attribute in stack? Obg!

  • @lineout Yes, because every time you use a template value in a class, the class has to switch to template as well, otherwise you couldn’t specify that you wanted a template Pilha<int> or a Pilha<double>. In that case when instance Pilha<int> will force Node<int>.

  • I did it but inside the stack ta returning error: Type 'Node<T>' could not be resolved ... even though I also put the template indication in the Stack. In the struct there was no error.

  • @lineout See the code example in my error free answer in Ideone. I even left an instantiation of a new node in the constructor as an example.

  • It worked... Thanks @Isac !! ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.