C++来看下

来源:百度知道 编辑:UC知道 时间:2024/06/20 16:35:46
数组求和
#include<iostream.h>
class array
{
public:
array(){}
array(int a,int b)
{
row=a;
col=b;
p=new int[a*b];
}
friend array operator+(array &,array &);
void input()
{
cout<<"please input the member of the array"<<endl;
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
cin>>*(p+i*row+j);
}
}
}
void out()
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
cout<<*(p+i*row+j)<<" ";
}
cout<<endl;
}
}
int *p;
int row,col;
};
array operator+(array &r1,array &r2)
{
array r(2,3);
int i,j;
for(i=0;i<r.row;i++)
{
for(j=0;j<r.col;j++)
{
r.p[i*r.row+j]=r1.p[i*r.row+j]+r2.p[i*r.row+j];

我把这程序的格式改了下,更容易看懂,也作了注释
#include<iostream.h>
//------------------------------------------------------------------------------
//类array的定义
class array
{
public:
array(){} //无参构造函数
array(int,int);//声明带2个行参的构造函数
friend array operator+(array &,array &);//友元,这样可以直接使用私有数据
void input();//声明输入函数
void out();//声明输出函数
private://最好定义数据为私有,体现类的封装性;要不容易被乱用
int *p;
int row,col;
};
//------------------------------------------------------------------------------
//定义成员函数
array::array(int a,int b)//定义带2个行参的构造函数
{
row=a;
col=b;
p=new int[a*b]; //分配数组所需的空间
}

void array::input()//定义输入函数
{
cout<<"please input the member of the array"<<endl;
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
cin>>*(p+i*row+j);
}
}

void array::out()//定义输出函数
{
in