2014-02-17 34 views
-1

我正在嘗試從文件中獲取數據並將其存儲在我創建的對象中。我一直遇到分段錯誤,但我不確定是什麼造成的。下面是代碼:爲什麼在通過引用傳遞對象時會一直出現分段錯誤?

Object<string> populateObj(Object<string>&,string); 
string clean(string); 
int main(){ 
    string dictionaryFile; 
    ifstream inFile; 
    ofstream outFile; 
    Object<string> obj1; 
    cout << "Enter the name of the Dictionary file" << endl; 
    cin >> dictionaryFile; 
    obj1 = populateObj(obj1,dictionaryFile); 
} 
Object<string> populateObj(Object<string> &obj,string fileName){ 
    ifstream file; 
    string words = ""; 
    file.open(fileName); 
    if(file.is_open()){ 
    while(!file.eof()){ 
     file >> words; 
     obj.add(words); 
    } 
    } 
    else 
    cout << "could not open file..." << endl; 
    return obj; 
} 
+4

你在初始化bag1? –

+2

然後不通過引用:p雖然從它的外觀來看,這是一個XY問題(meta.stackoverflow.com/questions/66377/what-is-the-xy-problem)。這個代碼甚至不應該編譯。 – thang

+4

隨機猜測,'對象'不能被正確複製 – paulm

回答

3

這可能會或可能不會引起你的問題,但這是錯誤的:

if(file.is_open()){ 
    while(!file.eof()){ 
     file >> words; 
     obj.add(words); 
    } 
} 

嘗試,而不是:

while (file >> words) { 
    obj.add(words); 
} 

你原來的代碼測試EOF太儘早有用。

+0

我試過了,但仍然出現了分段錯誤。 – user2351234

+0

@ user2351234你的複製構造函數怎麼樣?你是否有一個?你在處理'Object'類中的資源嗎?順便說一句,你不應該從'populateObj()'返回。它應該是一個'void'函數。 – 0x499602D2

1
int main(){ 
    //... 
    Object<string> obj1; 
    //... 
    obj1 = populateObj(obj1,dictionaryFile); 
} 
Object<string> populateObj(Object<string> &obj,string fileName){ 
    //... 
     obj.add(words); 
    //... 
    return obj; 
} 

您不必要地覆蓋該對象。不要這樣做。雖然技術上它可以工作,但這是一個壞習慣(它指向你的複製操作員有一個bug)。

而是返回一個引用(如果有的話)並且不覆蓋該對象。此外,不要傳遞字典字符串的值,通過它通過const參考:

int main(){ 
    //... 
    Object<string> obj1; 
    //... 
    populateObj(obj1,dictionaryFile); 
} 
Object<string>& populateObj(Object<string> &obj,const string& fileName){ 
    //... 
     obj.add(words); 
    //... 
    return obj; 
} 
1

我期望問題是在您的對象類。如果你把你現有的代碼,並定義對象這個樣子,那麼它在運行時錯誤:

template<class T> class Object { 
public: 
    void add(T); 
}; 

template <class T> void Object<T>::add(T val) 
{ 
    cout << "Adding " << val << "\n"; 
} 

所以,你需要看看你的對象類,看看它爲什麼失敗。最有可能的地方是當對象被複制時返回它,然後複製回原來的obj1。該類是否分配內存,或使用不可複製構造的成員變量?

如果你拿出對象的不必要的回報,你可以通過避免複製來「修復」問題,但是你可能仍然想修復對象,否則這個問題可能只會在對象的某個地方出現時被複制。

相關問題