我有一个用 Visual C++ 创建的 DLL 项目和一个 CLR 项目。 在我的 DLL 项目中,我导出了一个“auto”类型的函数。
员工.h
extern "C" STAFFS_API auto GetStaffMap();
如果staff.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:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.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:\users\laptop-attendance\source\repos\amscpprest\amscpprest\staff.cpp
Error C2371 'Staffs::GetStaffMap': redefinition; different basic types
最佳答案
auto
不会延迟查找函数的返回类型。它只是让编译器自动查看实现以找出它是什么。您必须在 header 中手动声明返回类型,因为包含 header 的代码必须知道返回类型是什么。
关于c++ - 返回 'auto' 的函数在定义之前不能使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50147561/