对+进行了重载,然后进行两个类对象之间的加法运算,并通过深复制赋予另一个对象,但是,这个被赋予的对象在复制完成后却被析构了,不懂,请大佬们看一看。
对+进行了重载,然后进行两个类对象之间的加法运算,并通过深复制赋予另一个对象,但是,这个被赋予的对象在复制完成后却被析构了,不懂,请大佬们看一看。
// 矩阵.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "string"
using namespace std;
class matrix {
private :
int lines;
int rows;
int**ptr;
int c;
public:
matrix(int line, int row,int c);
matrix(matrix&c1);
~matrix();
void input();
void output();
matrix operator+(const matrix &c2)
};
matrix::matrix(int line, int row,int c)
{
c = c;
lines = line;
rows = row;
int **ptr1 = new int*[line];
ptr = ptr1;
for (int i = 0; i < line; i++)
{
ptr[i] = new int[row];
}
}
matrix::matrix(matrix &c1)
{
lines = c1.lines;
rows = c1.rows;
int **ptr1 = new int*[c1.lines];
ptr = ptr1;
for (int i = 0; i < lines; i++)
{
ptr[i] = new int[rows];
}
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < rows; j++)
{
ptr[i][j] = c1.ptr[i][j];
}
}
}
matrix::~matrix(){
cout << "ssss" << ptr[0][0] << endl;
cout << c << endl;
for (int i = 0; i < lines; i++)
{
delete[rows]ptr[i];
ptr[i] = NULL;
}
delete[]ptr;
ptr = NULL;
}
void matrix::input() {
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < rows; j++)
{
cin >> ptr[i][j];
}
}
void matrix::output() {
for (int i=0;i<lines;i++)
{
for (int j = 0; j < rows; j++)
{
cout << ptr[i][j];
}
cout << endl;
}
}
matrix matrix::operator+(const matrix &c2)
{
int a = c2.lines;
int b = c2.rows;
int f = c2.c;
matrix c3(a,b,f);
if (lines==c2.lines&&rows==c2.rows)
{
for (int i = 0; i < lines; i++)
{
for (int j = 0; j < rows; j++)
{
c3.ptr[i][j] = ptr[i][j] + c2.ptr[i][j];
}
}
}
else
{
cout << "这两个矩阵不能相加" << endl;
}
return c3;
}
int main()
{
matrix A1(1, 1,0), A2(1, 1,0), A3(1, 1,1);
A1.input();
A2.input();
A3 = A1 + A2;
A3.output();
return 0;
}