首页 > 解决方案 > 为什么我不能在 C++ 的主函数中定义函数?

问题描述

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

#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++visual-c++

解决方案


为什么会这样?

因为标准是这样说的。

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

#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);

推荐阅读