指针从C 中的函数返回类型
pointer return type from a function in C++
我试图运行此程序,其中迭代器通过方法传递。该方法应增加值加一个并将其返回。我有错误:c: c 预制文件 test2 main.cpp | 23 |错误消息:
无法转换'std :: list :: iterator {aka std :: _ list_iterator}'to'int*for groment'1'to'int*getValue(int*)'|
#include <iostream>
#include <list>
using namespace std;
int* getValue(int*);
int main ()
{
list<int>* t = new list<int>();
for (int i=1; i<10; ++i)
{
t->push_back(i*10);
}
for (list<int>:: iterator it = t->begin(); it != t->end(); it++)
{
cout<< getValue(it)<< "n"<<endl;
}
return 0;
}
int* getValue(int* data)
{
int* _t = data +1 ;
return _t;
}
有人知道如何纠正它吗?
您的错误实际上很漂亮。您的功能应该是这样的:
int getValue(list<int>::iterator data) // take an iterator instead of an pointer and return a int.
{
int _t = *data +1 ; dereference data to get the value at that location.
return _t;
}
在您的原始版本中,您正在使用int *
,它与列表迭代器不同。另外,您要返回指针而不是INT值。解除了,因此您可以在迭代器而不是迭代器本身表示的位置上递增值(列表迭代器甚至不可能)。
也很可能您不需要new
您的列表,只需使用具有自动存储持续时间的一个即可。更改:
list<int>* t = new list<int>();
to
list<int> t;
相关文章:
- 检查函数返回类型是否与STL容器类型值相同
- 警告:在函数返回类型 [-Wignore 限定符] 时忽略类型限定符
- 在 c++ 中将函数返回类型指定为模板参数
- 通过引用传递参数;函数返回类型是否必须为 VOID?
- 如何避免模板函数返回类型重复?
- 从类型bankAccount的返回值到函数返回类型int没有可行的转换
- 为什么在某些情况下从函数返回类型中删除 cv 限定符?
- 模板类内模板类的函数返回类型
- 为什么函数返回类型中不允许参数推导?
- 函数返回类型之前的"define"
- C++推断要隐式调用的模板函数返回类型
- 具有不同模板参数的函数返回类型
- 当函数返回类型为父类时,如何返回子类的对象?
- C++:在原型中声明"auto"函数返回类型仍然会导致在扣除错误之前使用"auto&quo
- C++14 'auto'能够获取函数返回类型,我们还需要 std::result_of<> 吗?
- 函数返回类型中的模板类型推断
- 嵌套模板类返回类型在 C++ 中的头文件中函数返回类型的语法
- C++重写 void 函数返回类型会导致生成失败
- 从函数内部推断函数返回类型
- C++嵌套类函数返回类型和命名空间