从对象打印二维矢量时出错
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);
}
}
相关文章:
- 将二维矢量传递给类
- 将值从二维数组输出到文本文件
- 我在二维向量中是否正确分配了内存
- 带结构的二维矢量:如何存储元素
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 在二维三角测量中添加约束时出错
- 在二维德劳奈三角测量中插入顶点时出错
- 从我的二维数组中设置和获取值时出错
- 在C++中使用二维数组作为参数时出错
- C++中使用二维数组的类出错
- 将字符串复制到二维字符数组时出错
- 为二维数组动态分配内存时出错
- 将可变大小的二维数组传递给函数时出错
- 从对象打印二维矢量时出错
- 在函数搜索模式中引用二维数组时出错
- 将二维数组传递给函数时出错