从数组调用方法不会更改对象
Calling methods from the array doesnt change the object
当我尝试从数组中的对象调用方法时,更改不会在代码的其余部分持续存在。
通过一些搜索,我看到数组中的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];
}
相关文章:
- 将对象数组的引用传递给函数
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 类对象数组的问题会导致崩溃
- Arduino C++在构造函数中用参数声明对象数组
- 使用对象数组对 SFML 进行动画处理
- C++ 对象数组堆栈溢出
- 如何将对象数组作为参数传递给模板
- 使用向量初始化参数化构造函数的对象数组
- 如何初始化对象数组?
- C++创建对象数组
- 在对象数组中搜索字符串并返回相应值的函数
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 为什么我在声明对象数组时不能使用 -> 运算符?
- 编译时生成应在构造函数中创建的非 constexpr 对象数组
- 使用 C++ 创建对象数组
- 对象数组打印空白字符串
- 重载运算符 [] 用于从对象数组中给出特定索引
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组