【问题标题】:Function Declaration in C++C++ 中的函数声明
【发布时间】:2014-01-21 20:05:45
【问题描述】:

我在 CPP 中有以下代码。

//My code

#include<iostream>
using namespace std;
int main()
{
    int a;
    int display();
    int printfun(display());// Function prototype
    printfun(9);//Function calling
    return 0;
}
int printfun(int x)

{
    cout<<"Welcome inside the function-"<<x<<endl;
}
int display()
{
    cout<<"Welcome inside the Display"<<endl;
    return 5;

}

编译时会抛出错误“Line8:'printfun' cannot be used as a function”。

但是当我在 display 函数中调用 printfun 时,同样的代码可以完美运行。

#include<iostream>
using namespace std;
int main()
{
    int a;
    int display();
    int printfun(display());// Function prototype
        return 0;
}
int printfun(int x)

{
    cout<<"Welcome inside the function-"<<x<<endl;
}
int display()
{
    printfun(9); // Function call
    cout<<"Welcome inside the Display"<<endl;
    return 5;

}

谁能解释一下这背后的原因?

【问题讨论】:

  • 而不是int printfun(display()); 尝试int printfun(int x)。如代码中所述,这两行声明了一个函数原型,稍后将在其中实现该函数。好吧,看看 Kugelman 的回答:D

标签: c++ function-prototypes


【解决方案1】:
int printfun(display());// Function prototype

那不是函数原型。是一个变量声明,相当于:

int printfun = display();

函数原型“可以”在 main() 中完成,但将它们放在源文件的顶部更为正常。

#include <iostream>

using namespace std;

// Function prototypes.
int display();
int printfun(int x);    

int main()
{
    int a;
    printfun(9);  // Function call.
    return 0;
}

// Function definitions.
int printfun(int x)
{
    cout << "Welcome inside the function-" << x << endl;
}

int display()
{
    printfun(9); // Function call.
    cout << "Welcome inside the Display" << endl;
    return 5;
}

【讨论】:

  • 感谢约翰的回复。但我的问题是,当我在另一个函数中而不是在 main 中进行函数调用时,修改后的代码(我已经发布)如何完美地将其视为函数原型?
  • 第二个代码sn-p还是有问题int printfun(display());创建了一个名为printfun的变量,并为其赋值display()的返回值。它编译的原因是因为对printfun(9) 的调用现在位于int printfun(int x) 的定义之后,因此该函数在此范围内。在第一个 sn -p printfun(9) 定义之前调用。
【解决方案2】:

在此声明中

int printfun(display());// Function prototype

您定义了一个名为 printfun 的 int 类型对象,该对象由函数调用 display() 的返回值初始化。它不是你想象的函数声明。

所以 printfun 是一个 int 类型的对象然后是表达式

printfun(9);//

没有任何意义,编译器发出错误。

在第二种情况下,代码被编译是因为函数 display 看到全局名称 printfun 被声明为函数名。 main 内部的 printfun 在 main 外部不可见。实际上,您对 main 中定义的局部变量和全局函数名使用相同的名称,全局函数名是在全局命名空间内声明的函数名。函数显示会看到这个全局名称。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2016-08-10
    相关资源
    最近更新 更多