我是新來的C++。 我想做一個由2D矢量指針組成的類。我正在創建一個將2D矢量作爲參數的對象。我正在嘗試使用pointer來引用這個2D矢量。這種編譯方式很好,但在執行時出現了分段錯誤。 我在這裏附上我的代碼。請幫忙!2D矢量指針作爲類的成員
# include <iostream>
# include <vector>
using namespace std;
class Vectorref {
vector<vector<float> > *vptr; // pointer to 2D vector
public:
Vectorref(vector<vector<float> >);
double getval(int,int);
};
Vectorref::Vectorref(vector<vector<float> > v)
{
vptr = &v;
}
double Vectorref::getval(int r, int c)
{
return (*vptr)[r][c];
}
int main(){
vector<vector<float> > A (3,vector<float>(3,2.0));
Vectorref B(A);
for(int i=0; i<3 ;i++){
for(int j=0; j<3; j++){
cout << B.getval(i,j) << "\t";
}
cout << endl;
}
return 0;
}
'vptr =&v;' - 'v'是一個自動變量;傳入參數的*副本*。您正在保存一個自動變量的地址,該構造函數在構造函數退出時將不再存在。 – WhozCraig
@WhozCraig我應該怎麼做呢? – jennifer