读书人

满载[]的一个小知识

发布时间: 2013-11-15 22:28:15 作者: rapoo

重载[]的一个小知识
还是问题学生我。。

看下面的简单代码


#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;

class Array
{
private:
int *a, len;

void inflate()
{
cout << _T("the array is inflating..." )<< endl;

int *b = (int *)malloc(sizeof(int) * len * 2);
for(int i = 0; i < len; i++)
{
b[i] = a[i];
}
len += len;
free(a);
a = b;
}

public:
Array(int size):len(size)
{
a = (int *)malloc(sizeof(int) * size);
}


int & operator[](int index)
{
if(index < 0)
throw 1;
if(index >= len)
inflate();

return a[index];
}

void trans()
{
for(int i = 0; i < len; i++)
{
cout << a[i] << endl;
}
}

};


void main()
{
Array a(15);
for(int i = 0; i < 20; i ++)
{
a[i] = i;
}
a.trans();
}


//输出结果
//******输出结果***********

//00417AE8
//0
//1
//2
//3
//4
//5
//6
//7
//8
//9
//10
//11
//12
//13
//14
//15
//16
//17
//18
//19
//-842150451
//-842150451
//-842150451
//-842150451
//-842150451
//-842150451
//-842150451
//-842150451
//-842150451
//-842150451

1.这个重载的概念没太懂。
operator[]里面做了啥,谁能给讲讲?
2.为什么输出0之前 输出了个//00417AE8
[解决办法]
int & operator[](int index)
{
if(index < 0)
throw 1;
if(index >= len)
inflate();

return a[index];
}
如果 你取得index小于你初始化的大小,他返回给你对应的a[index];如果超过len的大小会重新申请2倍的len大小内存,然后返回给你。。over。。。
重载就是 函数名相同,参数类型或者参数个数不同。。。。其实编译完之后的函数名都不一样,编译器有mangling重写函数签名。
第二个单步吧。。。
结贴给分
[解决办法]
所谓操作符重载就是对c++里的一些 操作符重新定义功能,想[] 这个本事只是对数组取对应下标的元素,这里在赋值的时候判断下标是否超过数组大小,若超过则对数组进行扩充,至于为什么0之前显示一个地址,应该是_T()造成的 把工程换成多字节的或者是去掉_T()就ok了

读书人网 >C++

热点推荐