注册 登录
编程论坛 C++教室

[求助]用NULL返回空类型时,出现错误error C2440: “return”: 无法从“int”转换为

trailblazer 发布于 2007-03-12 18:22, 4506 次点击



这是一个数组类的程序,在重载操作符[ ]时,若参数i非法,返回空值,但出现错误error C2440: “return”: 无法从“int”转换为“int &”,应该怎么实现?请教高手指点,谢谢!

运行环境vs2005

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

const int DefaultSize = 100;

template <class Type>
class Array
{
Type *elements; //数组存放空间
int ArraySize; //当前长度
void getArray ( ); //建立数组空间
public:
Array( int Size=DefaultSize );
Array( const Array<Type>& x );
~Array( ) { delete [ ]elements;}
Type& operator [ ] ( int i ); //取元素值
};

template <class Type>
void Array<Type>::getArray ( )
{
//私有函数:创建数组存储空间
elements = new Type[ArraySize];
if ( elements == 0 )
{
ArraySize = 0;
cerr << "Memory Allocation Error" << endl;
return;
}
}

template <class Type>
Array<Type>::Array ( int sz )
{
//构造函数
if ( sz <= 0 )
{
ArraySize = 0;
cerr << "非法数组大小" << endl;
return;
}
ArraySize = sz;
getArray ( );
}

template <class Type>
Type & Array<Type>::operator [ ] ( int i )
{
//按数组名及下标 i,取数组元素的值
if ( i < 0 || i > ArraySize-1 )
{
cerr << "数组下标超界" << endl;
return NULL; //error C2440: “return”: 无法从“int”转换为“int &”
}
else
return elements[i];
}

int _tmain(int argc, _TCHAR* argv[])
{
Array<int> a(3);
a[0] = 1;
a[1] = 2;
a[2] = 3;
for (int j = 0; j < 3; j++)
{
cout<<a[j]<<endl;
}

return 0;
}

8 回复
#2
csight2007-03-12 19:16
return NULL; //error C2440: “return”: 无法从“int”转换为“int &”
上句可去;(但这样也会修改其他地方的数据;不好;)
或者lz可以直接在住函数中判断i的范围;
本人也等待有更好的解决办法......
#3
trailblazer2007-03-12 19:37

多谢2楼的
感觉函数Type & Array<Type>::operator [ ] ( int i )
的返回类型是参数化数据类型Type,所以不能直接返回NULL,不知道C++对这种模板类型的数据类型是否有更好的解决方法

#4
wfpb2007-03-12 21:42

用assert吧,用断言就可以警告程序员错误的位置了。

#5
trailblazer2007-03-14 17:45
assert该怎么用,不太明白啊
#6
wfpb2007-03-16 13:43

template <class Type>
Type & Array<Type>::operator [ ] ( int i )
{
//按数组名及下标 i,取数组元素的值
if ( i < 0 || i > ArraySize-1 )
{
cerr << "数组下标超界" << endl;
return NULL; //error C2440: “return”: 无法从“int”转换为“int &”
}
else
return elements[i];
}
改为:

template <class Type>
Type & Array<Type>::operator [ ] ( int i )
{
      assert(i>=0&&i<ArraySize);
      return elements[i];
}

#7
trailblazer2007-03-17 10:12
wfpb 版主,
我用assert怎么总出现如下错误,
error C3861: “ASSERT”: 找不到标识符
是vs2005的问题吗?
在网上找了好久也不知道如何修改啊
#8
wfpb2007-03-17 12:18
#include &lt;cassert&gt;或者#include &lt;assert.h&gt;
#9
trailblazer2007-03-21 22:37
回复:(wfpb)#include 或者#include...

多谢了,这么简单的问题

1