我的数组类

问题及代码:

/*
 *copyright(c) 2016烟台大学计算机学院
 *All rights reserved
 *文件名称:test.cpp
 *作者:杨昊
 *版本:v6.0
 *
 *问题描述: 我的数组类
 *输入描述:无
 *程序输出:
*/

#include<iostream>
using namespace std;
class MyArray
{
private:
    int *arrayAddr; //保存一个有len个整型元素的数组的首地址
    int len;       //记录动态数组的长度
    int max;       //动态数组中的最大值(并非动态数组中必须要的数据成员)
public:
    MyArray(int *a, int n);
    ~MyArray();
    int getValue(int i);   //获得数组中下标为i的元素的值
    int getLen();          //返回数组长度
    int getMax( );         //返回数组中的最大值
};

//定义构造函数,构造函数要完成下面三个任务:
//(1)为各成员函数赋值,其中arrayAddr应该是为保存数据新分配的连续空间的首地址;
//(2)将a指向的数组中的数值,逐个地复制到新分配的空间中
//(3)getMax( )函数采取的策略是直接返回max,计算max的工作,由构造函数完成
MyArray::MyArray(int *a, int n)
{
    len=n;
    arrayAddr=new int[n];
    max=a[0];
    for(int i=0; i<n; i++)
    {
        arrayAddr[i]=a[i];
        if (max<a[i]) max=a[i];
    }
}
//析构函数的类外定义,释放指针型数据a所指向的空间
MyArray::~MyArray()
{
    delete [] arrayAddr;
}

int MyArray::getValue(int i)    //获得数组中下标为i的元素的值
{
    return arrayAddr[i];
}
int MyArray::getLen()    //返回数组长度
{
    return len;
}
int MyArray::getMax( )    //返回数组中的最大值
{
    return max;
}
int main()
{
    int b[10]= {75, 99, 90, 93, 38, 15, 5, 7, 52, 4};
    MyArray r1(b,10);
    cout<<"最大值:"<<r1.getMax()<<endl;
    int c[15] = {18,68,10,52,3,19,12,100,56,96,95,97,1,4,93};
    MyArray r2(c,15);
    int i,s=0;
    for(i=0; i<r2.getLen(); i++)
        s+=r2.getValue(i);
    cout<<"所有元素的和为:"<<s<<endl;
    return 0;
}






结果及总结:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值