如果我们在 main 之外提及函数声明(如以下代码中所注释),则可以接受。但是,如果我在 main 中提到函数声明,如下面的代码所示,那么在运行时,无论提供什么值(整数或浮点类型),都只会调用以 int 作为参数类型的区域,即无论提供何种数据类型,仅提供一种类型的函数(此处为 area(int))被重复调用。为什么会发生这种情况,函数声明有什么问题,我希望它得到澄清。提前致谢。
#include<iostream.h>
#include<conio.h>
//void area(int);
//void area(float);
void main()
{
int a;
float b;
void area(int);
void area(float);
clrscr();
cout<<"enter the length or breadth of square";
cin>>a;
area(a);
cout<<"enter the radius of the circle";
cin>>b;
area(b);
getch();
}
void area(int x)
{
cout<<"area of square "<<x*x;
}
void area(float x)
{
cout<<"\narea of circle "<<3.14*x*x;
}
最佳答案
如果在 main 中您只声明了一个参数类型为 int
的函数,就会出现您所描述的情况。例如
#include<iostream.h>
#include<conio.h>
void area(int);
void area(float);
int main()
{
int a;
float b;
void area(int);
clrscr();
cout<<"enter the length or breadth of square";
cin>>a;
area(a);
cout<<"enter the radius of the circle";
cin>>b;
area(b);
getch();
}
void area(int x)
{
cout<<"area of square "<<x*x;
}
void area(float x)
{
cout<<"\narea of circle "<<3.14*x*x;
}
在这种情况下,只会调用参数类型为 int
的函数,因为局部函数声明隐藏了全局命名空间中的函数声明。
否则,如果两个函数都在 main 中声明,并且只调用带有 int 类型参数的函数,则编译器有错误。
尽管一些编译器允许使用 void 类型,但请注意函数 main 应具有返回类型 int
。但是 main 的这种声明不符合 C++。
关于c++ - 在函数重载中,在主函数外部和内部的情况下,函数调用的顺序在函数声明中有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31261224/