c++ - 使用构造函数将双链表中的指针初始化为 NULL

标签 c++ syntax constructor doubly-linked-list

我正在尝试初始化 Dlist 类的新对象。声明新对象后,指针firstlast 应该是NULL。但是,当我首先和最后声明 Dlist temp 时 - 构造函数未被识别,编译器正在为它们提供类似 0x0 的值。我不确定为什么构造函数被识别。

// 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 为空。此外,通过构造函数的初始化列表更有效地完成类成员的初始化:

Dlist()
    : first(nullptr)
    , last(nullptr)
{ /* No assignment necessary */ }

当一个类被构造时,初始化列表被应用到在构造函数体被执行之前为对象获取的内存。

关于c++ - 使用构造函数将双链表中的指针初始化为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26209552/

相关文章:

c++ - C++中的复合辛普森规则

C++回文程序

Java - 强制 super() 调用使用特定依赖项中的构造函数

C++ 避免构造对象

c++ - 将名称(即宏)定义为空

c++ - 内联使用静态数据初始值设定项

r - 变量名中的反引号

c# - 抽象类的析构函数

mysql - 在 WordPress 中使用 MySQL 查询检索小部件数据

c# - 在构造类的新实例时,如何避免传递对父对象的引用?