// 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;
}
重载赋值运算符
最新推荐文章于 2024-08-14 17:41:01 发布