模板类中成员函数的返回值问题?

acqy 2006-08-27 04:43:53
template <class T> class MyClass {
private:
vector<T> list;
public:
T GetValue(int index)
{
if(index < 0 || index >= list.size()) return ???; // 这里到底应该返回什么值呢?
else return list.at(index);
}
};

上面的代码中,???这个地方应该怎么写呢?
...全文
330 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenhu_doc 2006-08-27
  • 打赏
  • 举报
回复
想了解一个派生的处理异常的类:

class isbn_mismatch

reference to:

http://linuxbbs.cn/forum/viewthread.php?tid=159&extra=page%3D1
chenhu_doc 2006-08-27
  • 打赏
  • 举报
回复
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;


template <class T> class MyClass {
private:
vector<T> list;
public:
MyClass(): list(10,1){}
T GetValue(int index)
{
if(index < 0 || index >= list.size())
{
throw out_of_range(string("out_of_range() is out of range"));
}
else return list.at(index);
}
};


int main()
{
MyClass<int> a;

try{
a.GetValue(10);
}catch(const out_of_range & msg )
{
cerr << msg.what() <<endl;
}

system("pause");
return 0;
}
chenhu_doc 2006-08-27
  • 打赏
  • 举报
回复
return T(); //用类型T的默认构造函数返回一个T对象。
//通过在调用函数中对返回值的判断可以得出GetValue 的状态

不过,用到异常处理是最好的选择了!
因为处在 out_of_range 的情况,没有合适的可返回值!
believefym 2006-08-27
  • 打赏
  • 举报
回复
或者return NULL;
believefym 2006-08-27
  • 打赏
  • 举报
回复
看错
超出index范围了还用得着返回吗?
assert(index>0 && index<=list.size());
believefym 2006-08-27
  • 打赏
  • 举报
回复
else return list.at(index);
楼主,这个else不会看吗?
OOPhaisky 2006-08-27
  • 打赏
  • 举报
回复
if(index < 0 || index >= list.size()) return T();
else return list.at(index);

65,184

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧