返回"auto"的函数在定义之前不能使用

A function that returns 'auto' cannot be used before it is defined

本文关键字:不能 auto 函数 返回 定义      更新时间:2023-10-16

我有一个用Visual c ++创建的DLL项目和一个CLR项目。 在我的 DLL 项目中,我导出了一个带有"auto"类型的函数。

员工.h

extern "C" STAFFS_API auto GetStaffMap();

如果是工作人员.cpp它有一个 std::map 返回类型。

std::map<int, std::string> staffMap;
auto GetStaffMap() 
{
return staffMap;
}

现在在我的 CLR 应用程序中, 我调用此函数:

#include <map>
#include "Staff.h"
std::map<int, std::string> staffMap = Staffs::GetStaffMap();

当我编译程序时,它有一个错误,上面写着:

C3779 'Staffs::GetStaffMap': a function that returns 'auto' cannot be used before it is defined.

更新

我试过了 员工.h

extern "C" STAFFS_API auto GetStaffMap() -> std::map<int, std::string>;

工作人员.cpp

extern "C" auto GetStaffMap() -> std::map<int, std::string> {
return staffMap;
}

但仍然有编译错误:

Error   C2526   'GetStaffMap': C linkage function cannot return C++ class 'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>>'  AmsCppRest  c:userslaptop-attendancesourcereposamscpprestamscppreststaff.h
Error   C2556   'std::map<int,std::string,std::less<int>,std::allocator<std::pair<const _Kty,_Ty>>> Staffs::GetStaffMap(void)': overloaded function differs only by return type from 'void Staffs::GetStaffMap(void)'   AmsCppRest  c:userslaptop-attendancesourcereposamscpprestamscppreststaff.cpp
Error  C2371 'Staffs::GetStaffMap': redefinition; different basic types

auto不会延迟找出函数的返回类型。它只是让编译器查看实现,以找出它auto的。您必须在标头中手动声明返回类型,因为包含标头的代码必须知道返回类型是什么。

你应该声明一个返回的类型,以便编译器知道它。

// Declaration
extern "C" STAFFS_API auto GetStaffMap() -> std::map<int, std::string>;
// Definition
extern "C" auto GetStaffMap() -> std::map<int, std::string>
{
return staffMap;
}