2017-10-21 62 views
1

我試圖創建一個變量是一個節點指針的別名。g ++返回錯誤,當我嘗試使用指針的別名

到目前爲止,我曾嘗試以下語法:

node* _p = &p; 

&

node* &_p = p; 

每當我試圖調用一個類功能(即_p->的GetData())或甚至參考使用別名(如果(_p == NULL))我得到一個錯誤,指出:

error: expected primary-expression before ‘;’ token 
      node* newnode = _p; 

我hav當我打電話時,e也嘗試在_p之前放置*或&,但它沒有幫助。

注:我用G ++

一個最小的,完整的,並且可驗證的例子(我認爲)編譯:列表類的插入函數內發生 的錯誤...

class node{ 
private: 
    int data; 
    node* next; 
    int mark; 
public: 
    node(int d = 0, node* n = NULL){ 
     data = d; 
     next = n; 
     mark = 0; 
    } 
    int getdata(){return data;} 
    node* getnext(){return next;} 
    int getmark(){return mark;} 
    void setdata(int x){data = x;} 
    void setnext(node* x){next = x;} 
    void setmark(int x){mark = x;} 
}; 
class list{ 
private: 
    node* L1; //head pointers to list1, list2, and freelist. 
    node* L2; 
    node* free; 
    node* front; 
public: 
    list(){ 
     front = new node(); //generate free list (empty) 
     free = front; 
     L1 = NULL; 
     L2 = NULL; 
     node* p = free; 
     for (int i = 1; i < 10; i++){ 
      p -> setnext(new node()); 
      p = p -> getnext(); 
     } 
     delete p; 
    } 

    void insert(int a, int x){ 
     if (free == NULL) { 
      cout << a << " is full. can't insert " << x << " into the list." << endl; 
      return; 
     } 
     if (a == 1) node* &list = L1; 
     else if (a == 2) node* &list = L2; 
     else { 
      cout << "not a valid list"; 
      return; 
     } 
     if (list == NULL){ 
      list = free; 
      free = free -> getnext(); 
      list -> setdata(x); 
      list -> setnext(NULL); 
     } 
     else { 
      node* p = list; 
      while (p -> getnext() != NULL) {p = p -> getnext();} 
      p -> setnext(free); 
      free = free -> getnext(); 
      p -> getnext() -> setnext(NULL); 
      p -> getnext() -> setdata(x); 
     } 
    } 
}; 
+1

請提供產生此錯誤的[mcve]。 – chris

+0

如果'p'是指向'node'的指針,請嘗試'node * _p = p;' – Knoep

+0

node *&list = L1; list = list-> getnext(); 第二行是我的實際代碼chris的一個例子。 – ggkfox

回答

1

if (a == 1) node* &list = L1; 
else if (a == 2) node* &list = L2; 

listifelse if內作用域。它在其他地方不存在。下面是用大括號的代碼,以使問題更加明顯:

if (a == 1) 
{ 
    node* &list = L1; 
} 
else if (a == 2) 
{ 
    node* &list = L2; 
} 

由於定只能在初始化坐下,你將不得不在其他地方移動的邏輯。你的代碼的結構並不容易。

幸運的是,您似乎並不需要這個參考。在這裏使用常規指針。

node* list; 
    if (a == 1) list = L1; 
    else if (a == 2) list = L2; 

編輯

正如在評論中指出離退休忍者,list需要做個參考。在這種情況下,我們曾經用一個函數來選擇正確的名單,以照顧唯一能夠座位參考的問題:

node* & getList(int a) 
{ 
    if (a == 1) 
    { 
     return L1; 
    } 
    else if (a == 2) 
    { 
     return L2; 
    } 
    else 
    { 
     throw std::runtime_error("not a valid list"); 
    } 
} 

注扔在失敗的例外。最好在insert以下的某處處理,因爲insert無法正確處理它。

修訂後的初始化看起來像

node* &list = getList(a); 

現在list由函數範圍的,坐在只有一次,仍然是一個參考。

相關問題