第二次课后作业

1.仔细阅读下面的二维数组类,要求:

(1)用析构函数代替delete_twodim函数;

(2)用构造函数代替init_twodim函数;

(3)添加拷贝构造函数;

(4)在主函数中实现如下功能:

(i)  通过键盘输入行号row和列号col;

(ii)  定义一个二维数组对象s1, 行为row,列为col;

(iii) 定义第二个二维数组对象s,不指定该对象的行号和列号;

(iv) 通过键盘输入给s1的row*col个元素赋值;

(v) 通过调用拷贝构造函数,使得s与s1具有相同的内容;

(vi)打印s1和s2.

#include <iostream>
#include <string>
#include <iomanip>
using  namespace std;

class twodim{
public:
bool init_twodim(int r,int c);
void delete_twodim()
	float getValue(int i,int j);
	void setValue(int i,int j,float f);
	void print_twodim();
	
private:
	int row;
	int col;
	float *a;
};

bool twodim::init_twodim(int r,int c)
{
	row=r;
	col=c;
	a=new float[r*c];
	if(a!=NULL)
		return true;
	else
		return false;
}
void twodim::delete_twodim()
{
	if(a!=NULL) 
	{
		delete []a;
		a=NULL;
	}
}	

float twodim::getValue(int i,int j)
{
	if(a!=NULL)
		return *(a+i*col+j);
	else
	{
		 cout<<"数组为空!";
		 return 0;
	}
}

void twodim::setValue(int i,int j,float f)
{
	if(a!=NULL)
		*(a+i*col+j)=f;
	else
		cout<<"数组为空!";
}

void twodim::print_twodim()
{
	cout<<"打印数组:"<<endl;
	if(a==NULL)
		return;
	for(int i=0;i<row;i++)
	{	
		for(int j=0;j<col;j++)
			cout<<setw(5)<<getValue(i,j);
		cout<<endl;
	}
}

 源码如下:

#include <iostream>
#include <string>
#include <iomanip>
using  namespace std;

class twodim
{
public:
	twodim(int r, int c);
	~twodim();
	float getValue(int i, int j);
	void setValue(int i, int j, float f);
	void print_twodim();
	twodim(const twodim&);
private:
	int row;
	int col;
	float *a;
};
twodim::twodim(int r, int c)
{
	row = r;
	col = c;
	a = new float[r*c];
	cout << "Construct is called!" << endl;
}
twodim::~twodim()
{
	delete[]a;
	cout << "Destructor is called!" << endl;
}
float twodim::getValue(int i, int j)
{
	if (a != NULL)
		return *(a + i * col + j);
	else
	{
		cout << "数组为空!";
		return 0;
	}
}
void twodim::setValue(int i, int j, float f)
{
	if (a != NULL)
		*(a + i * col + j) = f;
	else
		cout << "数组为空!";
}
void twodim::print_twodim()
{
	cout << "打印数组:" << endl;
	if (a == NULL)
		return;
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
			cout << setw(5) << getValue(i, j);
		cout << endl;
	}
}
twodim::twodim(const twodim& s1)
	{
		row = s1.row;
		col = s1.col;
		a = s1.a;
		cout << "Copy constructor is called!" << endl;
	}





int main()
{
	int r = 0;
	int c = 0;
	cout << "请输入行和列的值:" << endl;
	cin >> r >> c;
	twodim s1(r, c);
	cout << "请输入数组的值:" << endl;
	for (int i = 0; i < r; i++)
		for (int j = 0; j < c; j++)
		{
			float x;
			cin >> x;
			s1.setValue(i, j, x);
		}
	 twodim s = s1;
	cout << "s1数组的打印结果:" << endl;
	 s1.print_twodim();
	 cout << "s数组的打印结果:" << endl;
	 s.print_twodim();
	 return 0;
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值