重载赋值运算符

// overrideassignoperator.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

template <class T>
class Matrix
{
public:
	// brief : 构造函数
	// param : nil
	Matrix(int row, int col)
	{
		m_m = new T[row * col];
		m_row = row;
		m_col = col;
	}
	
	// brief : 拷贝构造函数
	// param : nil
	Matrix(const Matrix &m)
	{
		m_m = new T[m.m_row * m.m_col];
		m_row = m.m_row;
		m_col = m.m_col;
		memcpy_s(m_m, sizeof(T) * m.m_row * m.m_col, m.m_m, sizeof(T) * m.m_row * m.m_col);
	}

	// brief : 析构函数
	// param : nil
	~Matrix()
	{
		if(m_m)
			delete m_m;
		m_m = NULL;
		m_row = 0;
		m_col = 0;
	}
	
	// brief : 第一个重载赋值运算符
	// param : m 数据指针
	//         return 当前实例的引用
	Matrix &operator= (const T *m)
	{
		memcpy_s(m_m, sizeof(T) * m_row * m_col, m, sizeof(T) * m_row * m_col);
		return *this;
	}

	// brief : 第二个重载赋值运算符
	// param : m 矩阵
	//         return 当前实例的引用
	Matrix &operator= (const Matrix<T> &m)
	{
		if(this == &m)
			return *this;// 这个判定是为了支持拷贝本身
		if(m_m)
			delete m_m;
		m_m = new T[m.m_row * m.m_col];
		m_row = m.m_row;
		m_col = m.m_col;
		memcpy_s(m_m, sizeof(T) * m.m_row * m.m_col, m.m_m, sizeof(T) * m.m_row * m.m_col);
		return *this;
	}

public:
	T *m_m;
	int m_row;
	int m_col;
};

int _tmain(int argc, _TCHAR* argv[])
{
	// 定义2x2矩阵
	Matrix<float> M(2, 2);

	// 调用第一个重载赋值运算符,使用数组赋值
	float _M[4] = {0.1f, 0.2f, 0.3f, 0.4f};
	M = _M;

	// 调用第二个重载赋值运算符,拷贝矩阵本身
	M = M;

	// 调用拷贝构造函数,使用矩阵初始化
	Matrix<float> S = M;

	// 首先调用第二个重载赋值运算符,使用矩阵赋值,
	// 然后调用拷贝构造函数,使用矩阵初始化,进行嵌套拷贝
	Matrix<float> T = S = M;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值