中括号重载问题

来源:百度知道 编辑:UC知道 时间:2024/05/24 04:42:40
请帮忙实现 里面的重载行标和列标的[].

#include <iostream>
using namespace std;

class Matrix
{
public:
Matrix(int r=0,int c=0);
class Array
{
public:
int operator[](int j); //列标
};
Array & operator[](int i); //行标
private:
int row;
int col;
int * data;
};

Matrix::Matrix(int r,int c)
{
row=r;
col=c;
data=(r & c) ? new int[r*c] : NULL;
for(int i=0;i<r*c;i++)
data[i]=i;
}

int main()
{
Matrix m(10,10);
int tmp=m[2][2];
cout<<tmp<<endl;
return 0;
}
请帮忙改实现一下我写的代码里面的那两个重载函数.
dongping 的是一维的结果啊.

我的回答不是一维的哟,那我就写清楚一些了哟!说句实在话,你的Matrix矩阵本来就是用一维的数组来模拟二维的运算的嘛,这是对的呀!把一个一维数组按照行的序号和列号取值(列号实际上是相对于该行起始地址的偏移量),当然就可以得出这个位置上的数据了!

class Array
{
public:
int operator[](int j); //列标
};
类定义中缺少数据成员。
正确的定义应当是:
====================================
class Array
{
public:
Array(int *p)
{
data=p;
}
int operator[](int j) //列标
{
return data[j];
}
private :
int *data;
}; ///Array类的定义结束
列标重载的函数
Array & Matrix::operator[](int i); //行标
定义如下:
====================================
Array & Matrix::operator[](int i)
{
Array p(this->data + i * col);
return p;
}

为了防止下标越界,也可以使用更严格的列类:
这样,Array的定义就成了:
============================
class Array
{
public:
Array(int *p,int size1)
{
data=p;
size=size1;
}
int operator[](int j) //列标,已经防止越界
{
if(j>=size)
{
p