[英]Using a constructor to initilize pointers to NULL in a Double linked List
我正在嘗試初始化類Dlist的新對象。 聲明一個新對象后, 第一個和最后一個指針應為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為NULL。 同樣,通過構造函數的初始化列表可以更有效地完成類成員的初始化:
Dlist()
: first(nullptr)
, last(nullptr)
{ /* No assignment necessary */ }
構造類時,在執行構造函數的主體之前,將初始化列表應用於為對象獲取的內存。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.