• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

第6周项目2-我的数组类

武飞扬头像
Ticking
帮助2

问题描述:

  下面的程序,因为存在指针类型的数据成员,需要能完成深复制的构造函数。请补充完整构造函数和析构函数(其他不必动)。其中,构造函数要完成下面三个任务:
(1)为各成员函数赋值,按照深复制原则,其中arrayAddr应该是为保存数据新分配的连续空间的首地址;
(2)MyArray(int *a, int n)中,要将a指向的数组中的数值,逐个地复制到新分配的arrayAddr指向的空间中;
(3)getMax( )函数采取的策略是直接返回max(所以,计算max的工作,由构造函数完成)

代码:

#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( );         //返回数组中的最大值
};
MyArray::MyArray(int *a,int n)
{
    len=n;
    arrayAddr=new int[n];
    int i;
    max=0;
    for(i=0;i<n;i  )
    {
        arrayAddr[i]=a[i];
        if(a[i]>max)
            max=a[i];
    }
}
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;
}

运行结果:

学新通

学习心得:

构造函数和析构函数可以方便的做很多事情。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibgafi
系列文章
更多 icon
同类精品
更多 icon
继续加载