在C++中调用函数

Calling a function in C++

本文关键字:函数 调用 C++      更新时间:2023-10-16

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

#include <iostream>
using namespace std;
int func()
{
    cout << 1 + 4;
    return 0;
}
int main()
{
    int func();
}

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

您没有正确调用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;
}

你可以按函数的名称调用它。像 func();

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

上面的函数正在重新运行一个整数。 你返回 0。 为了使其更有用,返回 sum 并在 main 函数中捕获它。

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;
}

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