下标运算符重载[]+函数调用运算符()+重载赋值运算符+构造函数(POJ C++ 第4周)

描述
写一个二维数组类 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;
//类
class Array2 
{
private:
	int arr[10][10];
	// 在此处补充你的代码

public:
	//声明构造函数
	Array2();
	Array2(int, int);
	//重载赋值运算符
	Array2& operator=(const Array2& a);
	//重载操作符()和[]?????????
	int operator()(int i, int j);
	int* operator[](int i);
};

//默认的构造函数
Array2::Array2()
{
	arr[10][10] = {0};

}
//构造函数
Array2::Array2(int a, int b)
{
	arr[10][10] = { 0 };
}
//重载操作符[],支持二维数组下标用*,一维用&
int* Array2::operator[](int i)
{
	return arr[i];
}
//重载操作符()
int Array2::operator()(int i, int j)
{

	return arr[i][j];
}
//重载赋值运算符
Array2& Array2::operator=(const Array2& a)
{
	for (int i = 0; i < 10; i++)
		for (int j = 0; j < 10; j++)
		{
		 arr[i][j] = a.arr[i][j];
		}
	return *this;
}
int main() 
{
	Array2 a(3, 4);//构造函数,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;
}

猜你喜欢

转载自blog.csdn.net/try_again_later/article/details/81198513