[英]Using a constructor to initilize pointers to NULL in a Double linked List
I am trying to initialize a new object of a class Dlist. 我正在尝试初始化类Dlist的新对象。 After a new object is declared the pointers first and last are supposed to be NULL .
声明一个新对象后, 第一个和最后一个指针应为NULL 。 When I declare the Dlist temp first and last however- the constructor isn't being recognized and the compiler is giving them values like 0x0 .
但是,当我首先和最后声明Dlist temp时-构造函数未被识别,编译器将其赋值为0x0 。 I'm not sure why the the constructor being recognized.
我不确定为什么构造函数被识别。
// dlist.h
class Dlist {
private:
// DATA MEMBERS
struct Node
{
char data;
Node *back;
Node *next;
};
Node *first;
Node *last;
// PRIVATE FUNCTION
Node* get_node( Node* back_link, const char entry, Node* for_link );
public:
// CONSTRUCTOR
Dlist(){ first = NULL; last = NULL; } // initialization of first and last
// DESTRUCTOR
~Dlist();
// MODIFIER FUNCTIONS
void append( char entry);
bool empty();
void remove_last();
//CONSTANT FUNCTIONS
friend ostream& operator << ( ostream& out_s, Dlist dl);
};
#endif
// implementation file
int main()
{
Dlist temp;
char ch;
cout << "Enter a line of characters; # => delete the last character." << endl
<< "-> ";
cin.get(ch);
temp.append(ch);
cout << temp;
return 0;
}
0x0 is NULL. 0x0为NULL。 Also, initialization of class members is more efficiently done via the constructor's initialization list:
同样,通过构造函数的初始化列表可以更有效地完成类成员的初始化:
Dlist()
: first(nullptr)
, last(nullptr)
{ /* No assignment necessary */ }
When a class is constructed, the initialization list is applied to the memory acquired for the object before the body of the constructor is executed. 构造类时,在执行构造函数的主体之前,将初始化列表应用于为对象获取的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.