IntArray::IntArray(int s =10){
m_size =(s>0?s:10;);
m_ptr =newint[m_size];assert(m_ptr !=0)for(int i =0;i < m_size;i ++){
m_ptr[i]=0;}}
"=“和”[]"重载代码样例
IntArray.h文件
classIntArray{
public:IntArray(int=10);//on the condition that//the premise do not give the parameters//the function will take the parameters automatically~IntArray();
IntArray&operator=(const IntArray &);// the overload of the equalityint&operator[](int index);voidDisplayArrayInfo();private:int m_size;int*m_ptr;};
IntArray.cpp文件
#include"IntArray.h"#include<iostream>#include<assert.h>usingnamespace std;
IntArray::IntArray(int s){
m_size =(s>0?s:10);
m_ptr =newint[m_size];//attention:the result returned is address.//problem: the reason of judging the relationship of the address and the zero is bizzare.assert(m_ptr !=0);for(int i =0;i < m_size;i ++){
m_ptr[i]=0;}//initialize the value of the element of the array.}
IntArray::~IntArray(){
cout<<"deleting !!"<<endl;delete[]m_ptr;}
IntArray& IntArray::operator=(const IntArray &right){
if(&right !=this){
//judging the size of the this and the size of hte rightif(m_size != right.m_size){
delete[]this->m_ptr;
m_size = right.m_size;
m_ptr =newint(right.m_size);assert(m_ptr !=0);}for(int i =0;i < right.m_size;i++){
m_ptr[i]= right.m_ptr[i];}}return*this;// the reference is just the object itself.just return the * pointer.}int& IntArray::operator[](int index){
assert(0<=index && index <= m_size);return m_ptr[index];}void IntArray::DisplayArrayInfo(){
for(int i =0;i < m_size;i ++){
cout<<m_ptr[i]<<" ";}
cout<<endl;}