c++ - 为什么我不能在 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;
}
解决方案
为什么会这样?
因为标准是这样说的。
而且你不需要它,因为你可以在函数中定义一个类型:
#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);
推荐阅读
- android - 如何为低于 23 的 API 级别在图层列表中设置可绘制 (PNG) 宽度和高度?
- oauth-2.0 - 在 Spring Boot 和 OAUTH2 SalesForce 会话期间刷新令牌
- sparql - Marklogic Triple store 是否支持 Ontology 中的 SWRL?
- azure - 使用 Azure 认知搜索从 Docx 文件中检索相关数据
- c# - 通过文件夹名称检查 Google Drive 中是否存在文件夹(C#)
- terraform - Terraform - if 语句选择适当的变量
- swift - 将核心数据同步到 CloudKit 公共数据库
- python - 将 json 对象包装在另一个对象中
- javascript - 由于应用程序路径不正确,Electron 应用程序自动启动会显示一个额外的窗口
- google-apps-script - 谷歌应用脚本:如何通过 FTP 上传文件