【问题标题】:Declaring an Auto Function is causing an undefined error声明自动函数会导致未定义的错误
【发布时间】:2023-03-16 00:02:01
【问题描述】:

所以我尝试对 Reader 文件使用自动函数,当我在自己的 .cpp 文件和 .h 文件中声明它时,我收到错误:

'Reader':返回'auto'的函数在定义之前不能使用

但该函数在声明 main 函数的 .cpp 文件中完美运行。

Reader.cpp

auto Reader(std::string Location, int Value)
{
    //Code - I removed the code for simplicity sake
    return 1;
}

阅读器.h

auto Reader(std::string Location, int Value);

这是它在主函数中的调用方式:

    int Renderer = Reader("Engine.Setup", Test);

【问题讨论】:

  • main 中,编译器应该有权访问的是标头中的auto Reader(std::string Location, int Value); 声明,它没有提供关于Reader 返回的有用信息。您可能需要一个尾随返回类型。或者直接返回int
  • 这就是为什么我评论了 //Code 我的代码在哪里,但为了简单起见,我把 return 1;
  • 我想你没抓住我的意思。 Reader.cpp 知道Reader 返回什么。 Reader.h 没有,所以main 也不会知道,除非您包含 Reader.cpp 以获得完整的定义。但是包含一个 cpp 文件是一种非常恶劣的行为,以至于您的姓氏将被必须处理后果的程序员永远诅咒。
  • 此时我不会使用 auto
  • @user12826193 在正确使用auto的情况下,一般来说没有任何问题。但是这个例子不是auto的正确使用。

标签: c++ function auto


【解决方案1】:

您收到错误是因为,在编译 main.cpp 时,编译器无法在 reader.cpp 中看到推断的返回类型 Reader(),因此它不知道它是什么。

解决方法:显式声明Reader()的返回类型。

【讨论】:

    【解决方案2】:

    这是一个假设的 main.cpp

    #include <string>
    #include <Reader.h>
    
    int main ()
    {
        int Renderer = Reader("Engine.Setup", Test);
    }
    

    在预处理器处理include 语句后,它看起来像

    // contents of string. Goes on for miles so I won't reproduce it here.
    auto Reader(std::string Location, int Value);
    
    int main ()
    {
        int Renderer = Reader("Engine.Setup", Test);
    }
    

    在这个文件中没有任何地方是Reader clear 的返回类型,所以你必须给它一个提示。 Reader.cpp 知道返回类型是什么,因为它可以从函数的定义中推断出来,但 Reader.cpp 是一个不同的Translation Unit,将单独编译。 Main.cpp 完全不知道任何人知道返回类型,而 main.cpp 不知道什么,编译器不知道并报告错误。

    阻力最小的路径是明确声明

    int Reader(std::string Location, int Value);
    

    在 Reader.h 中。您还可以为提示提供尾随返回类型。

    auto Reader(std::string Location, int Value)-> int;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多