温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

自定义数组类(下标操作符重载)

发布时间:2020-07-29 05:32:30 来源:网络 阅读:521 作者:神ge 栏目:编程语言
#include <iostream>
using namespace std;

class Array{
public:
    Array(int size):m_data(new int[size]),m_size(size){}
    ~Array(void){
        delete[] m_data;
        m_data = NULL;
    }
    int& operator[](int i){ //常版本
        return m_data[i];
    } 
    int& operator[](int i)const{ //非常版本
        return const_cast<Array&>(*this)[i]; //复用非常版本
    }

private:
    int* m_data;//一个数组主要包括,数组的首部元素地址和数组的元素个数
    int m_size;
};
int main(void){
    Array a(10);
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    for(int i=0;i<10;++i){
        cout << a[i] << endl;
    }
    //1 2 3 0 0 0 0 0 0 0
    //注意:int* p = new int[10];初始化元素都为0
   
    return 0;
}

常对象只能调常版本,非常对象既能调非常版本,也能调常版本.


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI