从数组调用方法不会更改对象

Calling methods from the array doesnt change the object

本文关键字:对象 数组 调用 方法      更新时间:2023-10-16

当我尝试从数组中的对象调用方法时,更改不会在代码的其余部分持续存在。

通过一些搜索,我看到数组中的get()方法需要通过引用返回变量,但是当我尝试这样做时,出现了其他异常。 所以我尝试使用这个:

template<typename T>
T& Vector<T>::get(int pos)
{
if (pos > this->index || pos < 0)
{
return T&() ;
}
return &this->array[pos];
}

但是我得到了错误:

错误

C2760:语法错误:意外的标记"(",预期的"表达式">

我是C++的新手,任何帮助都值得赞赏,提前感谢。

首先,您需要在函数的开头声明模板类型 T。

template <typename T>

其次,您不能像这里那样返回对临时变量的引用。(这甚至不是正确的语法,就像伊戈尔评论的那样。

return T&();

您可能应该抛出一个异常。

throw std::out_of_range("Attempted to access out of bounds");

第三,您可以从代码中删除this->。该函数已经允许您访问结构的字段。

这给你留下了这个有效的代码片段。

template <typename T> T &Vector<T>::get(int pos) {
if (pos > index || pos < 0) {
throw std::out_of_range("Attepted to access out of bounds");
}
return array[pos];
}