簡體   English   中英

從對象打印二維矢量時出錯

[英]Error when printing a 2d vector from an object

美好的一天! 我正在制作一個矩陣類,應該打印出矩陣的函數會破壞程序。 我很確定邏輯是正確的,所以我可能在某個地方犯了一個愚蠢的錯誤。 事實是,我似乎找不到。

這是完整的搜索代碼:

#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;
    }
}

您的問題是,在構造函數中,您需要使用名為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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM