私は Java 開発者ですが、今は C++ ライブラリが必要ですが、この言語の経験はあまりありません。特に、ポインタ、参照、メモリ割り当てについてはいつも混乱します。これが、開発中のマトリックス クラスでエラーが発生する理由だと思います。
メインコード:
#include "stdafx.h"
#include "matrix.cpp"
void matrixtest();
int main()
{
matrixtest();
system("pause");
return 0;
}
void matrixtest()
{
// let's try 3x3 matrices
static const int arr1[] = {1, 2, 1, -1, 1, 2, 2, 3, -4};
static const int arr2[] = {0, 2, 2, 1, -1, 0, 3, 2, -2};
vector<int> values1(arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]));
vector<int> values2(arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]));
matrix A(values1, 3);
matrix B(values2, 3);
matrix sum = A + B;
sum.show();
matrix diff = A - B;
diff.show();
matrix prod = A * B;
prod.show();
}
matrix.cpp
興味深いコード:
matrix::matrix(vector<int> v, int r) : values(v), rows(r) {
values = v;
rows = r;
}
// [...]
matrix& matrix::operator += (const matrix& rhs) {
matrix result = (*this) + rhs;
(*this) = result;
return *this;
}
matrix matrix::operator + (const matrix& rhs) {
if (rows != rhs.rows || values.size() != rhs.values.size()) {
throw std::length_error("Matrices shapes mismatch");
}
matrix result(values, rows);
for (auto& i : values) {
result.values[i] = this->values[i] + rhs.values[i];
}
return result;
}
// [...]
void matrix::show() {
string delimiter = "";
for (auto& i : values) {
delimiter = "";
for (auto j = 0; j < values.size()/rows; j++) {
cout << delimiter << values[i * values.size()/rows + j]; // this is the line giving the error
delimiter = ",";
}
std::cout << std::endl;
}
}
完全なmatrix.hpp
ファイル:
#ifndef matrix_hpp
#define matrix_hpp
class matrix {
private:
std::vector<int> values; // size is found by values.size()
int rows; // columns is values.size()/rows
public:
matrix(vector<int>, int); // base ctor.
matrix(const matrix& rhs); // copy ctor.
matrix& operator=(const matrix& rhs); // assign. ctor.
~matrix(); // dtor.
int& operator () (int row, int column);
const int& operator () (int row, int column) const;
matrix operator + (int scalar) const;
matrix operator - (int scalar) const;
matrix operator * (int scalar) const;
matrix& operator += (int scalar);
matrix& operator -= (int scalar);
matrix& operator *= (int scalar);
matrix operator + (const matrix&);
matrix operator - (const matrix&);
matrix operator * (const matrix&);
matrix& operator += (const matrix&);
matrix& operator *= (const matrix&);
// should be private ??
void reshape(int newRows, int newColumns);
void show(); //used for dev. only
void range(int start, int defaultStep = 1);
void fill(int value);
void randint(int lowerBound, int upperBound);
};
#endif /* CMatrix_hpp */
このクラスは、マトリックスの例で与えられた例に基づいています。
エラーには、「0xC0000005: アクセス違反の読み取り場所 0x5820A694」が表示されます。したがって、メモリ割り当てが間違っている、および/または範囲外の配列がある、および/または「&」演算子をいじっていると推測しています。
編集:次のトレースが表示されます:
- この 0x00dffe24 {values={ size=9 } rows=3 } マトリックス *
したがって、マトリックスは存在しますが、何らかの理由でエラーが発生しています。