0
我寫了一個代碼來呈現一個類第三個需要其他兩個類的實例一,兩個分別,一切工作正常,直到我添加了一個矩陣Mat,並且方法get_Mat在第三個類,在代碼中它有名字第三,這段代碼不會產生任何錯誤信息,但是當它執行之前,直到返回0之前的行在main中,然後它終止,因爲編譯器遇到了錯誤,需要關閉,我希望你能幫我找到問題。使用C++的類中的二維數組
謝謝。
#include<iostream>
#include<vector>
#include <stdlib.h>
using namespace std;
class One // this the first class
{
private:
unsigned int id;
public:
unsigned int get_id(){return id;};
void set_id(unsigned int value) {id = value;};
One(unsigned int init_val = 0): id(init_val) {}; // constructor
~One() {}; // destructor
};
////////////////////////////////////////////////////////////////////
class Two // the second class
{
private:
One first_one;
One second_one;
unsigned int rank;
public:
unsigned int get_rank() {return rank;};
void set_rank(unsigned int value) {rank = value;};
unsigned int get_One_1(){return first_one.get_id();};
unsigned int get_One_2(){return second_one.get_id();};
Two(const One& One_1 = 0, const One& One_2 =0 , unsigned int init_rank = 0)
: first_one(One_1), second_one(One_2), rank(init_rank)
{
}
~Two() {} ; // destructor
};
/////////////////////////////////////////////////////////////
class Three // the third class
{
private:
std::vector<One> ones;
std::vector<Two> twos;
vector<vector<unsigned int> > Mat;
public:
Three(vector<One>& one_vector, vector<Two>& two_vector)
: ones(one_vector), twos(two_vector)
{
for(unsigned int i = 0; i < ones.size(); ++i)
for(unsigned int j = 0; j < ones.size(); ++j)
Mat[i][j] = 1;
}
~Three() {};
vector<One> get_ones(){return ones;};
vector<Two> get_twos(){return twos;};
unsigned int get_Mat(unsigned int i, unsigned int j) { return Mat[i][j];};
void set_ones(vector<One> vector_1_value) {ones = vector_1_value;};
void set_twos(vector<Two> vector_2_value) {twos = vector_2_value;};
};
///////////////////////////////////////////////////////////////////////
int main()
{
cout<< "Hello, This is a draft for classes"<< endl;
vector<One> elements(5);
cout<<elements[1].get_id()<<endl;
vector<Two> members(10);
cout<<members[8].get_One_1()<<endl;
Three item(elements, members);
cout<<item.get_ones()[3].get_id() << endl;
cout << item.get_Mat(4, 2) << endl;
return 0;
}
首先感謝您試圖幫助我發現代碼中出現了什麼問題,您看起來是唯一一位耐心閱讀代碼的英雄,第二位關於twos.size()我不想使用無論如何,這個想法是實現二維矩陣與指數有關的其他類的實例,最後我沒有明確的方式來調整上述代碼,如果可能的話請提及哪些部分必須是由什麼部分取代,我嘗試了一些選擇,但沒有工作。謝謝 – mazlor
正如我上面所說:你需要在代碼中的某處設置你的'Mat'對象的大小,然後才能使用它。在你當前的代碼中,「Mat」是一個0x0的矩陣,每當元素被訪問時它就會崩潰,因爲你沒有爲任何元素保留空間。如果你不知道如何去做,請查找「調整矢量C++大小」。 – Roberto
謝謝羅伯託。 – mazlor