我已經實現了矩陣類。它爲任意大小的矩陣動態分配內存。當使用我的矩陣乘法函數時,它只能在特定條件下工作。如果您有兩個N * M矩陣,則第一個矩陣的M必須等於第二個矩陣的N. 例如:矩陣乘法問題
//matrix constructor 'matrix M(n, m)
matrix A(2, 3), matrix B(3, 4);
//A and B can be multiplied because A_m == B_n
A * B; //this works!
//changing the size of n of the first matrix causes this to fail if n > m
matrix C(4, 3), matrix D(3, 5);
C * D; // program becomes unresponsive for unknown reasons, only happens when C_n > C_m
我的矩陣類和乘法函數。
#include <iostream>
class matrix{
private:
int rows, cols;
public:
int ** data;
int row();
int col();
matrix();
matrix(int, int);
//~matrix();
matrix operator*(matrix M);
matrix operator%(matrix M);
friend std::ostream & operator<<(std::ostream & os, matrix M);
};
功能:
#include "matrix.h"
using std::cout;
using std::endl;
matrix::matrix(int r, int c){
rows = r;
cols = c;
data = new int*[rows];
for (int i = 0; i< rows; i++){
data[i] = new int[cols];
}
for (int i = 0; i < rows; i++){
for (int j = 0; j < cols; j++){
data[i][j] = 0;
}
}
}
matrix::row(){
return rows;
}
matrix::col(){
return cols;
}
matrix matrix::operator*(matrix M){
if (this->col() == M.row()){
matrix result(this->row(), M.col());
int var = 0;
for (int i = 0; i < result.row(); i++){
for (int j = 0; j < result.col(); j++){
for (int k = 0; k < result.row(); k++){
var += this->data[i][k] * M.data[k][j];
}
result.data[i][j] = var;
var = 0;
}
}
return result;
}
else cout << "FAILED";
}
std::ostream & operator<<(std::ostream & os, matrix M){
for (int i = 0; i < M.row(); i++){
os << '|';
for (int j = 0; j < M.col(); j++){
os << M.data[i][j] << ' ';
}
os << "|\n";
}
os << '\n';
return os;
}
爲什麼不能在這些環境下工作的計劃?
好消息是,您沒有[代碼三](https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming))代碼中的問題,因爲您'重新實現*析構函數,copy-ctor或copy-assignment操作符。壞消息是,*原因*這不是問題,因爲它像篩子一樣泄漏。 – WhozCraig