2016-06-30 61 views
0

所以我試圖讓一個類變量是一個向量並將它傳遞給一些類函數。什麼我試圖做一個基本的版本是在捕獲以下內容:C++分割錯誤將類變量傳遞給類函數

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


class isingModel { 
    private: 
     int length; 

    public: 
     void set_values (int); 
     void ising_Iterator(vector<vector<int> > &); 
     vector<vector<int> > lattice; 
}; 


void isingModel::set_values (int l) { 
    length = l; 
    vector<vector<int> > lattice(length, vector<int>(length)); 

    for (int i=0;i<length;i++){ 
     for (int j=0;j<length;j++){ 
       int randNum = rand() % 2; // Generate a random number either 0 or 1 
       lattice[i][j]=2*(randNum-.5); //shift value so that it is either 1 or -1. 
     } 
    } 
} 

void isingModel::ising_Iterator (vector<vector<int> > & lattice) { 

    lattice[0][0]=1; 

} 



int main() { 
    int L; 
    cout << "Enter the length of the lattice: "; 
    cin >> L; 

    isingModel iModel; 

    iModel.set_values(L); 
    iModel.ising_Iterator(iModel.lattice); 
    return 0; 
} 

所以我有了一些功能的一類,但我的主要目標是使類變量矢量,然後把它傳遞給不同的功能。在這段代碼中,我創建了一個名爲lattice的向量,並在set_values中設置了它的值,然後通過引用將lattice傳遞給了ising_Iterator,並且想要在lattice中更改一些值。根據文檔和其他問題,我想我必須通過引用傳遞向量(因此函數聲明中的&)。但我似乎仍然遇到分段錯誤。我使用gdb發現問題出在ising_Iterator中,所以它必須是類函數ising_Iterator不能訪問晶格向量。其中一個我很困惑的原因是,如果我有

void isingModel::ising_Iterator (vector<vector<int> > & lattice) { 

    length=1; 

} 

更換

void isingModel::ising_Iterator (vector<vector<int> > & lattice) { 

    lattice[0][0]=1; 

} 

一切編譯並運行良好。所以我的結論是,通過類變量是向量類的功能和改變它們有本質的區別則只是路過類變量類的功能,改變他們那裏..

回答

2
vector<vector<int> > lattice(length, vector<int>(length)); 

你覺得這是在做什麼?它實際上做的是聲明一個函數本地vector與成員變量相同的名稱。這陰影/隱藏成員,並且意味着您實際上正在更改本地作用域變量,而不是持久成員 - 因爲重複的名稱是「勝利」,它是最接近的作用域中的一個。

因此,您要更改方法​​中名爲lattice的局部變量。根據定義,這種變化無法達到任何功能。然後,局部變量超出範圍,不會被複制或以其他方式「發送」到任何地方,因此對它的所有更改都是無關緊要的。

您稍後嘗試訪問名爲lattice方法ising_Iterator()成員變量,假定你已經改變了它具有非零大小,失敗,因爲你沒有。關於索引,繁榮:段錯誤。

無論如何,你認爲你爲什麼必須在實例函數中傳遞任何成員變量?所有方法都可以完全訪問類成員。這是...使用一個類的全部點。在成員函數之間傳遞成員變量 - 儘管最後的猜測是錯誤的,而且如果正確地完成則工作得很好 - 最好是毫無意義,最壞的情況是浪費資源。

刪除局部陰影,停止傳遞成員的引用,並直接在方法中使用成員變量。它會工作。