实现数组类(C++ 拷贝构造函数、拷贝函数)要判断赋值左右对象不相等,坑惨了...
生活随笔
收集整理的這篇文章主要介紹了
实现数组类(C++ 拷贝构造函数、拷贝函数)要判断赋值左右对象不相等,坑惨了...
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include <iostream>
using namespace std;
class ArrayIndexOutOfBoundsException{ // 異常類
public:int index;ArrayIndexOutOfBoundsException(int k){index = k;}
};
class Array{
private:int *data;int size;static const int dSize = 10; // 數(shù)組默認(rèn)大小
public:Array( ){ // 無參構(gòu)造size = dSize;data = new int[size]( );}Array(int n ){ // 有參構(gòu)造size = n;data = new int[size]( );}Array(const Array& arr)//拷貝構(gòu)造函數(shù),深拷貝{if(arr.size>0) { size = arr.size;data = new int[size]( );for (int i = 0; i < size; i++){data[i] = arr.data[i];}}}Array& operator = (const Array& arr){if(this!=&arr)//如果等號右側(cè)的對象和左邊的不是一個對象再賦值(沒有這句會運行error),要判斷賦值左右對象不相等,坑慘了 {delete []data;//先釋放掉之前的內(nèi)存,否則會內(nèi)存超限 size = arr.size;data = new int[size]( );for (int i = 0; i < size; i++){this->data[i] = arr.data[i];}}return *this;}~Array() {if (this->data != NULL)//不為空才釋放 {delete []data;}}int& operator [] (int k){ // 運算符 [ ] 重載,以方便數(shù)組的使用if(k<0 || k>=size) throw ArrayIndexOutOfBoundsException(k);return data[k];}friend ostream& operator << (ostream& o, const Array& a); // 運算符 << 重載,以方便輸出
};
ostream& operator << (ostream& o, const Array& a){o << '[' ;for(int i=0; i<a.size-1; i++)o << a.data[i] << ',' ;o << a.data[a.size-1] << ']';return o;
}
// 注意:實際測試程序中,在此處之前的代碼與樣例中相同
// 注意:實際測試程序中,在此處之后的代碼(即main函數(shù))可能與樣例中不同
int main(){int n, k;cin >> n >> k;Array a(n); // 構(gòu)造數(shù)組,大小為 nfor(int i=0; i<n; i++) a[i] = i;Array b = a; // 拷貝構(gòu)造數(shù)組b[n/2] = k;cout << a << endl;cout << b << endl;Array c; // 構(gòu)造數(shù)組,默認(rèn)大小c = a; // 拷貝數(shù)組c[n/2] = k;cout << a << endl;cout << c << endl;a = a;a[n/2] = 2223;cout << a << endl;return 0;
}
轉(zhuǎn)載于:https://www.cnblogs.com/cstdio1/p/11080172.html
總結(jié)
以上是生活随笔為你收集整理的实现数组类(C++ 拷贝构造函数、拷贝函数)要判断赋值左右对象不相等,坑惨了...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【深入学习iOS开发(五)】Archiv
- 下一篇: [转]android使用shape st