C++中在类中对数组操作的注意事项

C++中对数组对象操作的注意实现

  • 判定传入的地址是否为空。采用断言去判定,0的含义和空的含义相同
assert(address != 0;
 要学会使用断言来确保程序的各个参数正常运行
  • 在成功申请内存的情况下,对数组的各个元素进行初始化
  for(int i = 0 ;i < m_size;i ++)
    {
    
    
        m_ptr[i] = 0;
    }

总结如下

IntArray::IntArray(int s = 10)
{
    
    
    m_size =(s>0?s:10;);
    m_ptr = new int[m_size];
    assert(m_ptr != 0)
    for(int i = 0 ;i < m_size;i ++)
    {
    
    
        m_ptr[i] = 0;
    }
}

"=“和”[]"重载代码样例

  • IntArray.h文件
class IntArray
{
    
    
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 equality
    int& operator[](int index);
    void DisplayArrayInfo();
private:
    int m_size;
    int *m_ptr;

};
  • IntArray.cpp文件
#include "IntArray.h"
#include <iostream>
#include <assert.h>

using namespace std;

IntArray::IntArray(int s)
{
    
    
    m_size =(s>0?s:10);
    m_ptr = new int[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 right
        if(m_size != right.m_size)
        {
    
    
            delete []this->m_ptr;
            m_size = right.m_size;
            m_ptr = new int(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;
}

猜你喜欢

转载自blog.csdn.net/Blackoutdragon/article/details/108813211