找了半天了,麻煩幫我看下。
///////////头文件
#ifndef POSTMASTER_H_INCLUDED
#define POSTMASTER_H_INCLUDED
#include<iostream>
#include <stdio.h>
#include <tchar.h>
using namespace std;
class Matrix
{
int rows, columns;
int **element;
void init(int rows, int columns);
public:
Matrix(int rows, int columns,int x);
~Matrix();
friend ostream& operator<<(ostream& out, Matrix&);
};
#endif // POSTMASTER_H_INCLUDED
////////////////////.cpp
#include "wine.h"
void Matrix::init(int rows, int columns)
{
element = new int*[rows];
this->rows = rows;
this->columns = columns;
for (int i = 0;i < columns;i++)
{
element[i] = new int[columns];
}
}
Matrix::Matrix(int rows, int columns, int x)
{
this->init(rows, columns);
cout << "1";
for (int i = 0;i < rows;i++)
for (int j = 0;j < columns;j++)
{
element[i][j]=x; ///这里貌似出错了?
}
}
Matrix::~Matrix()
{
for (int i = 0;i < rows;i++)
{
delete element[i]; //delete[] element[i]; ?
}
delete element;
}
ostream& operator<<(ostream& os, Matrix&a)
{
os<< "矩阵(" << a.rows << "," << a.columns << "):" << endl;
for (int i = 0;i < a.rows;i++)
{
os<< endl;
for (int j = 0;j < a.columns;j++)
os << a.element[i][j]<<" ";
}
return os;
}
//////////////////main()
#include "wine.h"
#include "wine.cpp"
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
int b[3][2] = { 1,2,3,4,5,6 };
Matrix a(3,2,4);
cout << a;
system("PAUSE");
return 0;
}
大家讲道理2017-04-18 10:55:42
錯誤的關鍵在這一行:
element[i][j] = x;
這種尋址的使用方式會嘗試存取element(首位址)+i*sizeof(int*)+j*sizeof(int)。
最好還是乖乖地使用:
int* row = element[i];
row[j] = x;
比較穩一些,也不怕不同的編譯器有不同的解釋方法。