第十五周上機任務項目1-建立專門的數組類處理有關數組的操作

來源:互聯網
上載者:User
01./*02.* 程式的著作權和版本聲明部分03.* Copyright (c)2013, 煙台大學電腦學院學生04.* All rightsreserved.05.* 檔案名稱: MyArray.cpp06.* 作    者:趙冠哲07.* 完成日期:2013年6月7日08.* 版本號碼: v1.009.* 輸入描述:10.* 問題描述:11.*/#include <iostream>using namespace std;class MyArray{private:    int *arr;//用於存放動態分配的數組記憶體首地址    int size;//數組大小public:    MyArray(int sz=50);    MyArray(int a[],int sz);//由一個內建類型的數組初始化    MyArray(const MyArray &A);//複製建構函式    ~MyArray(void);//解構函式,注意釋放空間    MyArray&operator =(const MyArray &A); //重載“=”使得數組對象可以整體賦值    bool operator == (MyArray& A);//重載==,使得Array對象能整體判斷兩個數組是否相等(size相等且對應元素相等)    friend ostream& operator << (ostream& out,MyArray& A);//重載<<,輸出數組    int GetSize(void) const;//取數組大小;};//以下為類成員函數的定義MyArray::MyArray(int sz){    size=sz;    arr=new int[size];    for(int i=0;i<size;++i)    *(arr+i)=0;}MyArray::MyArray(int a[],int sz){    size=sz;    arr=new int[size];    for(int i=0;i<size;++i)    *(arr+i)=*(a+i);}MyArray::MyArray(const MyArray &A){    size=A.size;    arr=new int[A.size];    for(int i=0;i<A.size;++i)    *(arr+i)=*(A.arr+i);}MyArray::~MyArray(void){    delete []arr;}MyArray& MyArray::operator=(const MyArray &A){    size=A.size;    arr=new int[A.size];    for(int i=0;i<A.size;++i)    *(arr+i)=*(A.arr+i);    return *this;}bool MyArray::operator == (MyArray& A){    bool compare=false;    double sum1=0,sum2=0;    for(int i=0;i<size;++i)    {        sum1=sum1+*(arr+i);        sum2=sum2+*(A.arr+i);    }    if(sum1==sum2)        compare=true;    return compare;}ostream& operator << (ostream& output,MyArray& A)  //重載<<,輸出數組{    for(int i=0;i<A.size;++i)    output<<*(A.arr+i)<<"  ";    cout<<endl;    return output;}int MyArray::GetSize(void)const //取數組大小;{    return size;}    //測試函數int main(){    int a[10]= {1,2,3,4,5,6,7,8,9,10};    int b[10]= {4,5,6,7,8,9,10,11,12,13};    MyArray arr1(a,10);  //測試用內建的數組初始化新定義的數組對象    MyArray arr2(b,10);    MyArray arr3(10);   //測試只指定大小的新數組對象的初始化    cout<<arr1;    //測試對<<的重載    cout<<arr2;    //測試對<<的重載    cout<<arr3;    //測試對<<的重載    cout<<"The size of arr1 is: "<<arr1.GetSize()<<endl;   //測試GetSize()成員函數    return 0;}

運行結果:

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.