Thursday 30 November 2017

c++ - Issue with Constructor of Struct nested in Class Template

itemprop="text">

I need to turn a linked list class for
ints that I wrote into a class template. I'm having issues with the constructor and
destructor for a struct nested in the List Class, called node.



Layout:




template
class List
{


public:
//Stuff that's not important to this question

private:
struct Node
{
Node(T value); //
constructor
~Node(); // destructor
Node *next; // pointer to the
next Node
T data; // the actual data in the node
static int
nodes_alive; // count of nodes still allocated

};

};


Implementation:



template

typename List::Node::Node(T
value)
{
data = value;

next =
0;
}

template
typename
List::Node::~Node()
{

--nodes_alive;
}



Errors:




  1. Expected ';' at
    end of declaration



    typename List::Node::Node(T
    value)


  2. Expected an identifier or
    template ID after '::'



    typename
    List::Node::~Node()


  3. Expected the class
    name after '~' to name a
    destructor




    typename
    List::Node::~Node()




Not
really sure what's going on here. My implementation is in a separate file included at
the bottom of the header file. Any help would be greatly appreciated.


style="font-weight: bold;">

Answer




It's simple: Get rid of the
typename keyword. Since you're writing a constructor/destructor
and there is no return type, it is not
needed.



template             T>
List::Node::Node(T value)

{

data = value;
next = 0;
}

template

List::Node::~Node()
{

--nodes_alive;
}



No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...