我在教育目的开发的c ++项目中找不到问题。在这里,我将发布我的代码并解释我发现问题的位置(感谢一些调试),我只是无法弄清楚为什么这是一个问题:
#include <string>
#include <iostream>
#include "Matrix.h"
int main() {
using namespace std;
cout << "<--------------- MATRIXES --------------->\n";
// Dimensions
const int HEIGHT = 3;
const int WIDTH = 4;
// Multi-dimensional int array
int A[HEIGHT][WIDTH] = {
{0, 1, 2, 4},
{1, 0, 2, 1},
{1, 1, 5, 8}
};
// Multi-dimensional int vector built with data from A
std::vector<std::vector<int>> Am(HEIGHT);
for (int i = 0; i < HEIGHT; ++i)
Am[i].resize(WIDTH);
for (int i = 0; i < HEIGHT; ++i)
for (int j = 0; j < WIDTH; ++j)
Am[i][j] = A[i][j];
// Everything before this comment works fine
// WORKING constructor for my Matrix
Matrix<int> M(Am);
// The problem is in the M.toString() call,
// in the next code block i will explain exatcly where
cout << "Matrix M:\n" << M.toString() << "\n";
return 0;
}
这是我项目的main.cpp,这是Matrix.h文件:
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
template <class T>
class Matrix{
std::vector<std::vector<T> > M;
int HEIGHT;
int WIDTH;
public:
Matrix();
Matrix(std::vector<std::vector<T> > m) {
HEIGHT = m.size();
WIDTH = m[0].size();
std::vector<std::vector<T> > M(HEIGHT);
for (int i = 0; i < HEIGHT; ++i)
for (int j = 0; j < WIDTH; ++j)
M[i].push_back(m[i][j]);
};
std::string toString() {
std::cout << M[0][0];
std::string r = "";
/*for (int i = 0; i < HEIGHT; ++i) {
for (int j = 0; j < WIDTH; ++j) {
if (j != WIDTH - 1)
r += std::to_string(M[i][j]) + " ";
}
if (i != HEIGHT - 1)
r += "\n";
}*/
return r;
}
};
代码会更大,但我评论了这篇文章中没有的所有内容,因为你可以看到toString方法只打印M [0] [0]返回“”,执行“停止工作”正好在std :: cout << M [0] [0],我想出无论在哪里,但当我尝试访问多维向量M时,它停止工作,它给了我:“进程退出返回值3221225477”。
有任何想法吗?
PS:我正在使用Windows 10,我有同样的问题使用clang和dev-c ++编辑:它看起来像Matrix构建(我已经测试过它,它构造得正确)但是程序忘记了矩阵是怎样的并试图访问它就像试图访问一个空的向量...不知道为什么..
将构造函数更改为
Matrix(std::vector<std::vector<T> > const & m) : M(m) {}
这也将解决阴影问题。您也可以从Matrix类中删除HEIGHT和WIDTH。
这可以通过两种方式解决问题。首先,它解决了构造函数的原始定义中的阴影问题,因为局部变量具有相同的名称M
,阴影类成员,M
。其次,它直接通过M
初始化类成员m
,而原始定义中不存在冗余副本。
主文件可能如下所示
#include <string>
#include <iostream>
#include "Matrix.h"
int main() {
using namespace std;
cout << "<--------------- MATRIXES --------------->\n";
vector<vector<int> > Am { { 1, 1, 1 },
{ 2, 2, 3 },
{ 6, 7, 8 } };
Matrix<int> M(Am);
cout << "Matrix M:\n" << M.toString() << "\n";
}