C++ 返回结构数组c++;

C++ 返回结构数组c++;,c++,struct,C++,Struct,我试图从函数返回结构,但出现错误: [错误]无法将“(数据*)(&Data)”从“数据*”转换为“数据” 这是我的结构: struct Data { string id, marc, model; }; 这就是我试图返回结构的实际操作: Data ReadFile (string file) { Data data[200]; ifstream in; in.open(file.c_str(), ios::in); if(!in) { cout<<"Error"&

我试图从函数返回结构,但出现错误:

[错误]无法将“(数据*)(&Data)”从“数据*”转换为“数据”

这是我的结构:

struct Data
{
    string id, marc, model;
};
这就是我试图返回结构的实际操作:

Data ReadFile (string file)
{
Data data[200];
ifstream in;
in.open(file.c_str(), ios::in);
if(!in) 
{
    cout<<"Error"<<endl;
    main();
}
else
{
    int i=0;
    while(getline(in, data[i].id, '\n'))
    {
        getline(in, data[i].marc, '\n');
        getline(in, data[i].model, '\n');
        i++;
    }
    in.close();
    cout<<"End"<<endl;
    main();
}
return data;
}
数据读取文件(字符串文件)
{
数据[200];
如果输入;
in.open(file.c_str(),ios::in);
如果(!in)
{

让我们考虑一下你的函数结构:

Data ReadFile (string file)
// ^ this function returns a 'Data' class
{
    Data data[200];
    // ^^^^^^^^^^^ here you declare a LOCAL array of 200 'Data's
    // ... stuff ...
    return data;
    //     ^^^^ here you try to return a 'Data*' 
}
这里我们有两个问题(更不用说任何设计考虑):

  • 您试图返回一个指针,而不是函数声明所期望的单个结构

  • 数组“data”是本地的,其生存期仅限于函数的范围

现在,您可以通过为数组动态分配内存来解决这些问题,在将函数的返回值更改为指针后返回指针(并记住在某个地方删除),但我建议使用
std::vector
,并将所有内存管理留给标准库类

std::vector<Data> ReadFile(std::string file)
{
    std::vector<Data> data;
    std::ifstream in{file};
    if ( !in ) 
    {
        cout << "Error opening file " << file << std::endl;
    }
    else
    {
        // Now, it's not clear how data are stored in your file.
        // Assuming something like:
        //   
        //   id1
        //   marc1
        //   model1
        //   id2 
        //   ...
        Data tmp;
        while(    getline(in, tmp.id) 
               && getline(in, tmp.marc)
               && getline(in, tmp.model) )
        {
            data.push_back(tmp);
        }
        std::cout << data.size() << " Data structs succesfully read.\n";
    }
    return data;
}
std::vector ReadFile(std::string文件)
{
std::矢量数据;
{file}中的std::ifstream;
如果(!in)
{

不能使用
std::vector
而不是
数据[200];
。调用
main()真是个坏主意
anywhere。我相信你可以用一些循环和if实现同样的效果。我想在这种情况下,
std::array
std::vector
更合适,因为你已经知道数组的大小。不需要浪费动态内存。`调用
main()实际上是未定义的行为
yourself in C++@DeiDei在我看来,代码应该读取一个文件,因此向量更合适(OP可能使用固定大小的数组,因为他不知道运行时大小的容器)。您的解决方案对我来说的问题是,函数必须是:Data ReadFile(string);我不能改变这一点。我非常喜欢在函数之间访问struc…@Gui61如果
Data
是您发布的结构,那么像
Data ReadFile(string)
这样的函数将读取(并返回)一次只能有一个struc。您确定必须传递的字符串是文件名吗?也许您的任务是使用该函数将字符串(从文件中读取的一行)转换为数据结构,并且每次读取一行时都必须调用它(在另一个函数中)我的想法是创建一个向量,并添加项目,但我疯了,这样做在C++,像这样(Stutt DATA数据[200);