【发布时间】:2018-02-04 00:03:16
【问题描述】:
所以我这里有这段代码:
template <class T>
T& Array<T>::operator[](const int pos){
// Exit if pos is not valid.
if (pos < 0 || pos >= mSize) {
return -1;
}
return mArray[pos];
}
我收到了这个错误:
error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int'
我知道它正在发生,因为我在开头有引用 &T,如果它通过 if 语句无效,我将返回 -1。尽管我想拿出参考资料,但这是一个学校实验室,我无法调整原型。 所以基本上我的问题是:如果 if 语句在没有编辑任何引用的情况下通过,我如何让它以 -1 退出? 我知道我可能在某个时候已经学会了这一点,但我有有点脑子放屁,寻找最后一点没有结果。
【问题讨论】:
-
要返回一个引用,你必须在某个地方(不是函数本地)有一个
T,你可以返回一个引用。虽然不是一个很好的界面设计,因为这会阻止您在数组中存储 -1。