2009-11-01 62 views
1

我正在構建一個應用程序,該應用程序爲給定目錄中的項目構建一個結構向量,並返回要讀取的向量的引用,嘗試編譯示例時收到以下錯誤下面的代碼:返回向量堆棧參考的問題

1. 'class std::vector<indexStruct, std::allocator<indexStruct> >' has no member named 'name' 
2. no matching function for call to `std::vector<indexStruct, std::allocator<indexStruct> >::push_back(std::vector<indexStruct, std::allocator<indexStruct> >&)' 

exampleApp.cpp

#include "exampleApp.h" 

exampleApp::exampleApp() 
{ 
    this->makeCatalog(); 
} 

char* findCWD() 
{ 
    char* buffer = new char[_MAX_PATH]; 
    return getcwd(buffer, _MAX_PATH); 
} 

void exampleApp::makeCatalog() 
{ 
    char* cwd = this->findCWD(); 
    vector<indexStruct> indexItems; 

    this->indexDir(cwd, indexItems); 
} 

void exampleApp:indexDir(char* dirPath, vector<indexStruct>& indexRef) 
{ 
    DIR *dirPointer = NULL; 
    struct dirent *dirItem = NULL; 
    vector<indexStruct> indexItems; 
    vector<indexStruct> indexItem; 

    try 
    { 
     if ((dirPointer = opendir(dirPath)) == NULL) throw 1; 
     while (dirItem = readdir(dirPointer)) 
     { 
      if (dirItem == NULL) throw 2; 
      if (dirItem->d_name[0] != '.') 
      { 
       indexItem.name = dirItem->d_name; 
       indexItem.path = dirPath; 
       indexItems.push_back(indexItem); 
       indexItem.clear(); 
      } 
     } 

     indexRef.swap(indexItems); 
     closedir(dirPointer); 
    } 
    catch(int errorNo) 
    { 
     //cout << "Caught Error #" << errorNo; 
    } 
} 

exampleApp.h

#ifndef EXAMPLEAPP_H 
#define EXAMPLEAPP_H 

#include <iostream.h> 
#include <dirent.h> 
#include <stdlib.h> 
#include <vector.h> 
using namespace std; 

struct indexStruct 
{ 
    char* name; 
    char* path; 
}; 

class exampleApp 
{ 
public: 
    exampleApp(); 
private: 
    char* findCWD(); 
    void makeCatalog(); 
    void indexDir(char* dirPath, vector<indexStruct>& indexRef); 
}; 

#endif 

我在這裏做錯了什麼,有沒有更好的方法去做這件事?

+0

哪條線是錯誤? – Mark 2009-11-01 17:59:24

回答

0

你讓「indexItem」一個載體,你可能只是希望它是你希望把「indexItems」類型。此外,我會在你的循環中創建新的結構:

while (dirItem = readdir(dirPointer)) 
    { 
     if (dirItem == NULL) throw 2; 
     if (dirItem->d_name[0] != '.') 
     { 
      indexStruct indexItem; 

      indexItem.name = dirItem->d_name; 
      indexItem.path = dirPath; 
      indexItems.push_back(indexItem); 
     } 
    } 
+0

我已將代碼更改爲您建議的內容,並且這是新的編譯錯誤: 'struct indexItem'沒有名爲'clear'的成員 removed indexItem.clear();修復它,但現在我想知道如果我需要銷燬它被推入到載體後的indexItem結構? – 2009-11-01 18:14:36

+0

是的,清楚不應該在那裏,對不起。如果你不使用'新',你不需要擔心刪除任何東西。 indexItem將被複制到任何使用它的地方。它被複制到向量中,並且當包含'if'的範圍被留下時,局部被銷燬。 – joshperry 2009-11-01 18:32:08

+0

好的謝謝你的幫助,現在一切正常! – 2009-11-01 18:35:17

0

你要定義一個名爲vectorindexItem

vector<indexStruct> indexItem; 

這僅僅是一個數組。所以,以下行必須改變,以引用向量的特定元素:

indexItem.name = dirItem->d_name;// should be indexItem[..].name or indexItem.at(..).name 
indexItem.path = dirPath;  // same as above! 
+0

我已經改變了代碼,就像你說的那樣,它編譯時沒有任何錯誤,但exe運行並沒有任何錯誤或任何事情就死了。 – 2009-11-01 18:09:53