2009-10-23 41 views
1

我有編譯錯誤不合格-ID

class Node 
{ 
public: 

string el1; 
string el2; 
string curr; 
string name; 
int ID1; 
int ID2; 

Node(){ 
//constructor is here 
ID1=-1; 
ID2=-1; 
} 

}; 

而且它具有與陣列表示10個不同的節點..

Node [] allNode=new Node[10]; 

for(i=0; i< 10; i++) 
{ 
//create new node 
allNode[i] = new Node(); 

std::string el = "f"; 
std::string el2 = "g"; 
std::string allNode[i].curr; 

allNode[i].curr = name + boost::lexical_cast<std::string>(i); 
cout << "Node name " << allNode[i].curr <<endl; 

} 

然而,我有編譯錯誤如下: -

error: expected unqualified-id before ‘[’ token referring to Node [] allNode=new Node[10]; 
error: ‘allNode’ was not declared in this scope 
error: ‘name’ was not declared in this scope 

請指教。謝謝。

+0

馬丁格式化源代碼對你,但你應該這樣更有意義自己格式化,當你擁有所有的標籤和回報,你可以很容易地發現在它的錯誤.. – Zenuka 2009-10-23 07:47:56

回答

1

代碼中存在多個問題。第一個new Node[10]返回第一個對象的地址,所以你的語句應該是Node* allNode = new Node[10];。我不確定這條語句的意思是什麼:std::string allNode[i].curr

2

在C++中,你把方括號放在變量名後面,例如:

Node allNode[10]; 

然而,與動態分配的數組打交道時,使用指針類型:

Node *allNode = new Node[10]; 
0

誤差來源於此行:
Node [] allNode=new Node[10]; 這應該是:
Node* allNode=new Node[10];

您也沒有正確訪問節點的成員。請參見下面的示例代碼:

int main 
{ 
    Node* allNodes = new Node[10]; 

    for(i=0; i< 10; i++) 
    { 
    //create new node 
    allNodes[i] = new Node(); 

    allNodes[i]->el = "f"; 
    allNodes[i]->el2 = "g"; 
    allNodes[i]->curr = name + boost::lexical_cast<std::string>(i); 

    std::cout << "Node name " << allNodes[i]->curr << std::endl;  
    } 

    delete [] allNodes; 
}