Thursday, 7 December 2017

c++ - What is wrong with my ctor using linked list and templates?

itemprop="text">

I am trying to practice a little bit
with cpp and want to make a class of linked list and than to manipulate it reverse it,
finding circle and etc. but I can't understand what is the problem with my ctor/



I have this
main:




#include
"list.h"
#include


using
namespace std;


int main () {
int x =
10;


ListNode node4();

ListNode node3(10
,node4);
}


while
this is "list.h" :



#ifndef
LIST_NODE_H
#define LIST_NODE_H


#include

using namespace std;

template T>
class ListNode {

ListNode* next;
T
data;


public:

ListNode(
T dat = 0 ,const ListNode &nex =
NULL):data(dat),next(nex){};

};

#endif


I
can't understand why this line: ListNode node3(10
,node4);


makes this errors, what is the
problem?




list.cpp:
In function ‘int main()’: list.cpp:12:33: error: invalid
conversion from
‘ListNode ()()’ to ‘int’ [-fpermissive]
list.h:15:3: error:
initializing argument 1 of
‘ListNode::ListNode(T, const ListNode&) [with
T = int]’
[-fpermissive] list.cpp:12:33: warning: passing NULL to
non-pointer
argument 1 of ‘ListNode::ListNode(T, const ListNode&) [with T
=
int]’ [-Wconversion-null] list.cpp:12:33: error: recursive
evaluation

of default argument for ‘ListNode::ListNode(T, const
ListNode&)
[with T = int]’ list.h:15:3: warning: in passing argument 2
of
‘ListNode::ListNode(T, const ListNode&) [with T = int]’
[enabled
by default] list.h: In constructor ‘ListNode::ListNode(T,
const
ListNode&) [with T = int]’: list.cpp:12:33: instantiated
from
here list.h:15:76: error: cannot convert ‘const ListNode’ to

‘ListNode
’ in
initialization



class="post-text" itemprop="text">
class="normal">Answer



You have a
number of errors with your
code:





  1. In
    your constructor you have a null reference as your default
    value, which is invalid (see href="https://stackoverflow.com/questions/4364536/c-null-reference">here).


  2. For
    a constructor with no arguments you need to omit the () (you
    can read about why href="https://stackoverflow.com/questions/180172/why-is-it-an-error-to-use-an-empty-set-of-brackets-to-call-a-constructor-with-no">here)




Something
like this should work:



using
namespace std;


template
class
ListNode {
ListNode* next;
T data;


public:
ListNode( T dat = 0 ,ListNode * nex =
NULL):data(dat),next(nex){};
};



int
main(){
ListNode node4;
ListNode node3(10,
&node4);
}


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 ...