【问题标题】:Why can't I define a function within the main function in C++? [duplicate]为什么我不能在 C++ 的主函数中定义函数? [复制]
【发布时间】:2020-11-13 12:07:50
【问题描述】:

如果我实现函数原型并在主函数之后定义它,这个程序可以正常工作。 为什么会这样?

#include <iostream>
using namespace std;

typedef unsigned short UShort;

main()
{
    UShort length, breadth, TotalArea;
    cout<<"Enter length and breadth";
    cin>>length>>breadth;

    UShort FindArea(UShort l, UShort b)
    {
    return l * b;
    }

    TotalArea = FindArea(length, breadth);
    cout<<"Total Area is "<<TotalArea;
}

【问题讨论】:

  • 我想有人可以提供一些历史解释 C 是如何开发的,它很难实现或类似的东西,但真的没有比“标准这么说”更好的答案了。
  • C++ 不允许在函数中定义函数。您可以改用 lambda。
  • 可能“Jerry Coffin”的回答最接近回答您的问题:why wasn't the idea of nested functions, implemented in older c++ standard?
  • main 必须具有显式返回类型int。当没有定义返回类型时,C++ 不支持隐式返回类型int

标签: c++ visual-c++


【解决方案1】:

为什么会这样?

因为标准是这样说的。

而且你不需要它,因为你可以在函数中定义一个类型:

#include <iostream>
using namespace std;

typedef unsigned short UShort;

int main()
{
    UShort length, breadth, TotalArea;
    cout<<"Enter length and breadth";
    cin>>length>>breadth;

    struct FindAreaType {
        UShort operator()(UShort l, UShort b) const
        {
            return l * b;
        }
    };
    FindAreaType FindArea;            

    TotalArea = FindArea(length, breadth);
    cout<<"Total Area is "<<TotalArea;
}

一个或多或少相同的更方便的方法是 lambda 表达式:

auto FindArea = [](UShort l, UShort b) { return l * b; };
TotalArea = FindArea(lenght,breadth);

【讨论】:

    【解决方案2】:

    实现您所要求的最佳方法是使用 lambda 而不是函数。

    // ...
    
    int main()
    {
        // ...
    
        // Define lambda instead of a function
        auto FindArea = [](UShort l, UShort b) { return l * b; };
    
        // Use defined lambda
        TotalArea = FindArea(length, breadth);
        // ... 
    }
    

    正如评论者所提到的,由于历史原因,C 中没有嵌入式函数。但从 C++11 开始,现在有了 lambda 表达式。

    从 C++17 开始,您甚至可以使用 auto 关键字代替 lambda 参数的显式类型。

    auto FindArea = [](auto l, auto b) { return l * b; };
    

    这样您就可以将FindArea 用于floatdouble 参数(或任何具有重载乘法运算符的参数)。

    【讨论】:

      猜你喜欢
      • 2010-11-06
      • 2015-07-10
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多