从对象打印2d向量时出错

时间:2013-07-06 12:27:54

标签: c++

美好的一天!我正在制作一个矩阵类,应该打印出矩阵的函数会破坏程序。我很确定逻辑是正确的,所以我可能在某处犯了一个愚蠢的错误。事情是,我似乎无法找到它。

以下是整个源代码:

#include <iostream>
#include <vector>
using namespace std;


class Matrix{
    private:

    double determinant;
   vector<vector <int> > body;
    int ROWS;
    int COLUMNS;
    public:
    int get_rows(){return ROWS;}
    int get_columns(){return COLUMNS;}
    vector<vector <int> > get_body(){return body;}
    //default constructor
    Matrix();
    //set up constructor
    Matrix(int rows, int columns);
};

//creates the matrix and let's the user fill it's value
Matrix :: Matrix(int ROWS, int COLUMNS){
     vector< vector<int> > body;
    this->ROWS = ROWS;
    this->COLUMNS = COLUMNS;
     for(int i = 0; i < ROWS; i++){
        cout<<"Row " << i << " begins" <<endl;
        vector<int> tmp;
        for(int z = 0; z < COLUMNS; z++){
            cout<<"Column "<< z<< " begins."<<endl;
            int temp;
            cin >> temp;
            tmp.push_back(temp);
        }
        body.push_back(tmp);
    }
}

//default constructor
Matrix:: Matrix(){
     vector< vector<int> > body;
}

void  print(Matrix a){
    for(int i = 0; i < a.get_rows(); i++){

        for(int z = 0; z < a.get_columns(); z++){
            cout<<a.get_body()[i][z];
        }
        cout<< endl;
    }
}
int main()
{
    Matrix a(2, 2);
    print(a);
    return 0;
}

破碎功能的主体:

void  print(Matrix a){
    for(int i = 0; i < a.get_rows(); i++){

        for(int z = 0; z < a.get_columns(); z++){
            cout<<a.get_body()[i][z];
        }
        cout<< endl;
    }
}

1 个答案:

答案 0 :(得分:-1)

您的问题是,在构造函数中,您处理名为body的局部变量而不是类成员。

Matrix :: Matrix(int ROWS, int COLUMNS){
//    vector< vector<int> > body;
//    ^^^^^^^^^^^^^^^^^^^^^^^^^^ this should not be here!
    this->ROWS = ROWS;
    this->COLUMNS = COLUMNS;
     for(int i = 0; i < ROWS; i++){
        cout<<"Row " << i << " begins" <<endl;
        vector<int> tmp;
        for(int z = 0; z < COLUMNS; z++){
            cout<<"Column "<< z<< " begins."<<endl;
            int temp;
            cin >> temp;
            tmp.push_back(temp);
        }
        body.push_back(tmp);
    }
}