You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode为何能编译无main()函数的C++程序?

LeetCode 为啥不用写 main() 函数?

其实根本不是从Solution类的第一个函数开始执行——LeetCode后台偷偷帮你生成了完整的main()函数,把你的代码拼进去一起编译运行。

具体流程是这样的:

  • 后台会根据你当前做的题目,生成对应的代码模板,里面包含标准的main()入口。
  • 这个模板会把你提交的Solution类包含进去,然后负责读取测试用例的输入、创建Solution实例、调用你实现的题目指定函数(比如两数之和的twoSum,不是看你写的第一个函数),最后把结果输出或者和标准答案对比。

举个直观的例子,假设你提交了题目里的那段代码,后台实际编译的代码大概是这样:

#include <iostream>
#include <string>
using namespace std;

// 你提交的代码原样插入
class Solution {
public:
    int foo(string s) {
        int ans = 0;
        // <work>
        return ans;
    }
 };

// 后台自动生成的main函数
int main() {
    string testInput;
    cin >> testInput;
    Solution solutionInstance;
    int output = solutionInstance.foo(testInput);
    cout << output << endl;
    return 0;
}

核心要点:

  • 调用哪个函数是题目预先规定好的,和你写的函数顺序无关;
  • 你只需要专注实现题目要求的函数,输入输出、程序入口这些脏活累活全由后台模板搞定。

内容的提问来源于stack exchange,提问作者Shivani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 02:24:55