Rumah > Soal Jawab > teks badan
找了半天了,麻烦帮我看下。
///////////头文件
#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
Kunci kepada ralat ialah baris ini:
element[i][j] = x;
Cara menggunakan pengalamatan ini akan cuba mengakses elemen (alamat pertama)+i*sizeof(int*)+j*sizeof(int).
Sebaik-baiknya menggunakannya dengan patuh:
int* row = element[i];
row[j] = x;
Ia lebih stabil, dan kami tidak takut bahawa penyusun yang berbeza mempunyai kaedah tafsiran yang berbeza.