2

我是整个 C++ 编程的新手,我知道这是一个简单的解决方案,但我就是想不通!我只是想调用一个打印出 1 + 4 的函数。这是代码:

#include <iostream>
using namespace std;

int func()
{
    cout << 1 + 4;
    return 0;
}

int main()
{
    int func();
}

它在控制台窗口中没有显示任何内容,只是应用程序停止并返回代码 0。有人可以告诉我出了什么问题吗?

4

2 回答 2

6

您没有func()正确调用函数:

int main()
{
    // int func(); This line tries to declare a function which return int type.
    //             it doesn't call func()
    func();   // this line calls func() function, it will ouput 5
    return 0;
}
于 2013-09-29T11:07:54.637 回答
1

您可以直接按名称调用该函数。像 func();

int func()
{
    cout << 1 + 4;
    return 0;
}

上面的函数正在返回一个整数。您将返回 0。以使其更有用返回总和并在主函数中捕获它。

int func(){
    return 1+4;// return 5 to main function.
}

现在主要。

int main (){
     int ans = func();// ans will catch the result which is return by the func();
     cout<<ans;
     return 0;
}

尝试理解每个语句的工作原理。

于 2013-09-29T11:23:20.280 回答