C++如何重载双下标运算符实例源码介绍。我们很清楚矩阵和二维数组,但要实现双下标的重载还是需要动脑筋设计程序的,下面将提供两种方法解决这个问题,由于内容长无法一次发布,先发第一种方法:
方法一:只重载第一个下标,第二个下标借助下标本身的功能实现,这是一种偷懒的方法,不过形式上可以实现。
思路只需要一个类就可以搞定,我们起名叫做Matrix类,为让大家容易看清文件关系,下面会有分割线分隔不同的文件代码,请细心阅读:
//—————————————————————————————-
// matrix.h
//—————————————————————————————-
#ifndef MATRIX_H
#define MATRIX_H
class Matrix
{
public:
Matrix(int aRow, int aCol); //构造函数
~Matrix(); //析构函数
int *operator[](int aIndex); //重载下标运算符
private:
int m_iRow; //行数
int m_iCol; //列数
int *m_pRow; //每行数据的指针
};
#endif
//———————————————————————————
// matrix.cpp
//———————————————————————————
#include “matrix.h”
Matrix::Matrix(int aRow, int aCol)
{
m_iRow = aRow;
m_iCol = aCol;
m_pRow = new int[m_iRow];
for(int i = 0 ; i < m_iRow; i++)
{
//让int型变量存储对象指针
m_pRow[i] = reinterpret_cast<int>(new int[aCol]);
}
}
Matrix::~Matrix()
{
//注意销毁完每列对象后,销毁行
for(int i = 0 ; i < m_iRow; i++)
{
delete []reinterpret_cast<int *>(m_pRow[i]);
}
delete []m_pRow;
}
//返回值是一个从int 转为int*的指针
int *Matrix::operator[](int aIndex)
{
return reinterpret_cast<int *>(m_pRow[aIndex]);
}
//——————————————————————————-
// demo.cpp
//——————————————————————————-
#include <iostream>
using std::cout;
using std::endl;
#include “matrix.h”
int main()
{
Matrix matrix(10,10);
//给每个元素赋值
for(int i = 0 ; i < 10 ; i++)
{
for(int k = 0 ; k < 10 ; k++)
{
matrix[i][k] = 10;
}
}
//打印出每个元素
for(int i = 0 ; i < 10 ; i++)
{
for(int k = 0 ; k < 10 ; k++)
{
cout << matrix[i][k] << endl;
}
}
system(“pause”);
return 0;
}
本篇文章接上篇《C++如何重载双下标运算符(一)》,下面是第二种方法,这种方法的通用性较好,但仍然有不少改进的空间,有兴趣可以深入交流哦。
//———————————————————-
//
//———————————————————-
#ifndef ELEMENT_H
#define ELEMENT_H
class Element
{
public:
private:
};
#endif
//———————————————-
//
//———————————————-
#include “element.h”
Element::Element(int aData)
{
}
Element::~Element()
{
}
int Element::getData()const
{
}
//————————————————————-
//
//————————————————————-
#ifndef ROW_H
#define ROW_H
#include “element.h”
class Row
{
public:
private:
};
#endif
//——————————————–
//
//——————————————–
#include “row.h”
int Row::m_iSize = 1;
Row::Row()
{
}
Row::~Row()
{
}
//重载的【】符号
Element &Row::operator[](int aIndex)
{
}
void Row::setSize(int aSize)
{
}
//————————————–
//
//————————————–
#ifndef MATRIX_H
#define MATRIX_H
#include “row.h”
class Matrix
{
public:
private:
};
#endif
//——————————————–
//
//——————————————–
#include “matrix.h”
Matrix::Matrix(int aRow, int aCol)
{
}
Matrix::~Matrix()
{
}
Row &Matrix::operator[](int aIndex)
{
}
//—————————————————————-
//
//—————————————————————-
#include <iostream>
using std::endl;
using std::cout;
#include “element.h”
#include “matrix.h”
int main()
{
}
//————————————————————————–
看到这,你有没有把它写成模版类的冲动,如果有就动手试试吧。