北京大学C++程序设计coursera课程第四周编程填空题3

题目

填空题-3

1 point possible (graded)
总时间限制:
1000ms
内存限制:
65536kB
描述

写一个二维数组类 Array2,使得下面程序的输出结果是:

0,1,2,3,

4,5,6,7,

8,9,10,11,

next

0,1,2,3,

4,5,6,7,

8,9,10,11,

程序:

#include <iostream>
#include <cstring>
using namespace std;
// 在此处补充你的代码
int main() {
    Array2 a(3,4);
    int i,j;
    for(  i = 0;i < 3; ++i )
        for(  j = 0; j < 4; j ++ )
            a[i][j] = i * 4 + j;
    for(  i = 0;i < 3; ++i ) {
        for(  j = 0; j < 4; j ++ ) {
            cout << a(i,j) << ",";
        }
        cout << endl;
    }
    cout << "next" << endl;
    Array2 b;     b = a;
    for(  i = 0;i < 3; ++i ) {
        for(  j = 0; j < 4; j ++ ) {
            cout << b[i][j] << ",";
        }
        cout << endl;
    }
    return 0;
}
输入
输出
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,
样例输入
样例输出
0,1,2,3,
4,5,6,7,
8,9,10,11,
next
0,1,2,3,
4,5,6,7,
8,9,10,11,

答题:
#include <iostream>
#include <cstring>
using namespace std;
class Array2
{
  int *ptr;
  int row;//行数
  int col;//列数
public:
  Array2(int a,int b):row(a),col(b)
  {
    ptr=new int[row];
    for(int i = 0 ; i < row; i++)
    {
      ptr[i] = reinterpret_cast<int>(new int[col]); //把int* 转化成int
    }
  }
  Array2(){ptr=NULL;row=0;col=0;}
  ~Array2()
  {
    for(int i = 0 ; i < row; i++)
    {
      delete []reinterpret_cast<int*>(ptr[i]);
    }
    delete []ptr;
  }
  int* operator[](int a)
  {
    return reinterpret_cast<int*>(ptr[a]);
  }
  Array2& operator =(const Array2 &k)
  {
    if(ptr==k.ptr) return *this;
    if(ptr!=NULL)
    {
      for(int i = 0 ; i < row; i++)
      {
        delete []reinterpret_cast<int*>(ptr[i]);
      }
    delete []ptr;
    }
    if(k.ptr==NULL)
    {
      ptr=NULL;
      row=0;
      col=0;
      return *this;
    }

    ptr=new int[k.row];
    row=k.row;
    col=k.col;

    for(int i = 0 ; i < row; i++)
    {
      ptr[i] = reinterpret_cast<int>(new int[col]);
    }

    for(int i = 0 ; i < row; i++)
    for(int j = 0 ; j < col; j++)
      {(reinterpret_cast<int*>(ptr[i]))[j]=(reinterpret_cast<int*>(k.ptr[i]))[j];}
    cout<<"done"<<endl;
    return (*this);
  }
  int& operator()(int a,int b)
  {
    return (*this)[a][b];
  }
};
 
int main()
{
  Array2 a(3,4);
  int i,j;
  for( i = 0;i < 3; ++i )
  for( j = 0; j < 4; j ++ )
    a[i][j] = i * 4 + j;
  for( i = 0;i < 3; ++i )
  {
    for( j = 0; j < 4; j ++ ) 
    {
      cout << a(i,j) << ",";
    }
    cout << endl;
  }
  cout << "next" << endl;
  Array2 b;
  b = a;
  for( i = 0;i < 3; ++i )
  {
    for( j = 0; j < 4; j ++ )
    {
      cout << b[i][j] << ",";
    }
    cout << endl;
  }
  return 0;
}
 
核心难点是双[]运算符怎么重载出来,思想是第一个[]中放地址,然后第二个[]就可以用默认的寻址运算,这样只需要对第一个[]进行重载。
实现的过程中注意运用reinterpret_cast即c++的类型转换。





猜你喜欢

转载自www.cnblogs.com/xuhaoforwards/p/9248638.html