指针从C 中的函数返回类型

pointer return type from a function in C++

本文关键字:函数 返回类型 指针      更新时间:2023-10-16

我试图运行此程序,其中迭代器通过方法传递。该方法应增加值加一个并将其返回。我有错误: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;