构造函数、拷贝构造函数的运用

需求:

创建一个矩阵类,要求实现矩阵的乘法

矩阵元素的数据类型为float,矩阵用双重指针表示;

另外,程序要包含:构造函数、拷贝构造函数、析构函数。


代码:

//矩阵类头文件Matrix.h
#ifndef _MATRIX_H_
#define _MATRIX_H_

typedef float DataType;

#define ROW 3//矩阵的行
#define COL 4//矩阵的列

class Matrix
{
public:
	Matrix(int row, int col);//构造函数
	Matrix(Matrix&);//拷贝构造函数
	~Matrix();//析构函数
	

	//重载乘法*运算符,双目运算符重载为类的友元函数
	friend Matrix operator*(Matrix&, Matrix&);
	void Input();//矩阵输入函数
	void Display();//矩阵输出函数
private:
	int row;
	int col;
	DataType **matri;
};
#endif


//矩阵类实现文件Matrix.cpp
#include <iostream>
#include "Matrix.h"
using namespace std;

extern Matrix cMatrix;

//构造函数
Matrix::Matrix(int nRow, int nCol)
{
	row = nRow;
	col = nCol;
	matri = new DataType*[nRow];
	for (int i = 0; i < nRow; i ++)
		matri[i] = new DataType[nCol];
}

//拷贝构造函数
Matrix::Matrix(Matrix& Object)
{
	row = Object.col;//列数赋给行
	col = Object.row;//行数赋给列
	matri = new DataType *[row];
	for (int i = 0; i < row; i ++)
	{
		matri[i] = new DataType[col];
	}
}
//析构函数
Matrix::~Matrix()
{
	for (int i = 0; i < row; i ++)
		delete[] matri[i];
	delete[] matri;
}

//对矩阵乘法运算符的重载
Matrix operator*(Matrix& aMat, Matrix& bMat)
{
	for (int i = 0; i < cMatrix.row; i ++)
	{
		for (int j = 0; j < cMatrix.col; j ++)
		{
			DataType sum = 0;
			for (int k = 0; k < aMat.col; k ++)
			{
				sum += aMat.matri[i][k]*bMat.matri[k][j];
			}
			cMatrix.matri[i][j] = sum;
		}
	}
	return cMatrix;
}

//Input函数
void Matrix::Input()
{
	for (int i = 0; i < row; i ++)
	{
		for (int j = 0; j < col; j ++)
		{
			cin >> matri[i][j];
		}
	}
}

//Display函数
void Matrix::Display()
{
	for (int i = 0; i < row; i ++)
	{
		for(int j = 0; j < col; j ++)
		{
			cout << matri[i][j] << "  ";
		}
		cout << endl;
	}
}

//主函数处理文件main.cpp
#include <iostream>
#include "Matrix.h"
using namespace std;

Matrix cMatrix(ROW, ROW);

int main()
{
	Matrix aMatrix(ROW, COL);
	aMatrix.Input();

	Matrix bMatrix = Matrix(aMatrix);
	bMatrix.Input();

	aMatrix * bMatrix;
	cMatrix.Display();
	return 0;
}


测试实例:

5.6 6.5 9.8 4.2
5.9 4.6 9.8 4.7
6.2 1.9 3.2 5.5


1.87 2.69 4.23
5.55 6.23 4.29
1.99 5.69 7.41
5.26 3.16 6.89


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值