我正在尝试初始化 Dlist 类的新对象。声明新对象后,指针first 和last 应该是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/