重载二维数组a[i][j]为a(i,j)

重载函数调用运算符()的一个较好的例子是将 以下的二维数组的下标表示方法chessboard[row][column]改为常用方法chessBoard(row,column),试图调用运算符()扶持上述表示法

/*重载函数调用运算符()的一个较好的例子是将 以下的二维数组的下标表示方法chessboard[row][column]改为常用方法chessBoard(row,column)。
试图调用运算符()扶持上述表示方法*/
/*思路:构造一个类私有成员为数组,然后再写重载函数。*/

#include <iostream>
using namespace std;

class chessBoard
{
public:
	chessBoard();
	int operator()(int r,int c){return a[r][c];}
	void print()
	{
		for(int i=0;i<8;i++)
			for(int j=0;j<8;j++)
			{
				cout<<a[i][j];
				if(j==7)
					cout<<endl;
			}
	}
private:
	int a[8][8];
};
chessBoard::chessBoard()
{
	for(int i=0;i<8;i++)
		for(int j=0;j<8;j++)
			a[i][j]=j;
}
int main()
{
	chessBoard a;
	a.print();
	cout<<"a(3,3)="<<a(3,3)<<endl;
	system("pause");
	return 0;
}
posted @ 2010-10-30 21:53  瓜蛋  阅读(1523)  评论(0编辑  收藏  举报