我試圖創建一個不同尺寸的矩陣,它可以正常工作5乘3或3乘3但如果我嘗試製作2乘3矩陣,那麼我得到一個不好的過剩碼。換句話說,如果我嘗試在我的(x,y)對中使我的x比我的y小,那麼我就會變得不合格。C++多維數組壞多餘代碼
在我的頭文件我有:
#ifndef fasdf_dynn_h
#define fasdf_dynn_h
#include <iostream>
#include <fstream>
#include<string>
#include <cstdlib>
#include <vector>
using namespace std;
template <class T>
class MatrixdynVector{
public:
MatrixdynVector();
MatrixdynVector(int m,int n);
MatrixdynVector(T diagonal, int n, int m);
template <class H>
friend ostream& operator <<(ostream& outs, const MatrixdynVector<H> &obj);
private:
int m,n;
int** matrix;
};
#endif
,並在我的cpp文件我有:
#include "dynn.h"
template <class T>
MatrixdynVector<T>::MatrixdynVector(){
//creates a 3 by 3 matrix with elements equal to 0
m=3;
n=3;
matrix=new int*[m];
for(int i=0;i<m;i++)
matrix[i]=new int[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
matrix[i][j]=0;
}
template <class T>
MatrixdynVector<T>::MatrixdynVector(int x,int y)
{
//creates a matrix with dimensions m and n with elements equal to 0
m=x;
n=y;
matrix=new int*[m];
for(int i=0;i<m;i++)
matrix[i]=new int[n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
matrix[i][j]=0;
}
template <class T>
ostream& operator <<(ostream& outs, const MatrixdynVector<T> & obj)
{
for (int i = 0; i < obj.m; i++){
for (int j = 0; j < obj.n; j++)
outs << " "<< obj.matrix[i][j];
outs<<endl;
}
outs<<endl;
return outs;
}
int main()
{
MatrixdynVector<int> B;//works fine
MatrixdynVector<int> A(2,3);//bad excess
cout<<B;
cout<<A;
}
過量?訪問?你的析構函數在哪裏?爲什麼你不使用矢量? – deviantfan
@deviantfan我已經做了這與矢量,但我需要做到這一點與動態數組和解析器不是目前的問題 – Brogrammer