话说在C/C++语言中,不能在一个函数里面定义另外一个函数,但是没有说不可以声明,于是就声明了一个试试。
- #include <iostream>
- using namespace std;
- int main()
- {
- int fun();
- cout<<"hahah"<<endl;
- fun();
- return 0;
- }
- int fun()
- {
- cout<<"this int int itn fun"<<endl;
- }
但是有什么意义呢?它与下面这段函数的意义是相同的。至少在表面上是这样:
- #include <iostream>
- using namespace std;
- int fun();
- int main()
- {
- cout<<"hahah"<<endl;
- fun();
- return 0;
- }
- int fun()
- {
- cout<<"this int int itn fun"<<endl;
- }
但是想想,这与在函数外部声明函数有什么区别呢?这个体现出了C与C++的区别。
先看C代码:
- #include <stdio.h>
- void aprintfun()
- {
- printf("this is in the function aprintfun/n");
- fun();
- }
- int main()
- {
- int fun();
- fun();
- printf("hahahah,this is a funny test/n");
- aprintfun();
- return 0;
- }
- int fun()
- {
- printf("this is in the fun function/n");
- }
只有在函数定义为int类型的时候才可以这样用,定义为void不行,定义为double也不行。
而对于C++,这样用是完全行不通的,试过把函数定义为int,定义为void,都不行,提示出错:
error:fun was not declared in this scope
代码如下:
- #include <iostream>
- using namespace std;
- void aprintfun()
- {
- cout<<"aprintfun/n";
- fun();
- }
- int main()
- {
- void fun();
- cout<<"hahah"<<endl;
- fun();
- aprintfun();
- return 0;
- }
- void fun()
- {
- cout<<"this int int itn fun"<<endl;
- }
综合上面所说,在C++中,可以在一个函数里面声明一个新的函数,但是只能在这个函数内使用这个新的函数,新函数的定义一定在放在这个函数的外面。
如果想在另外的一个函数中用新函数的话,是不可以的,除非再声明一个。
在C语言中,可以在一个函数里面声明一个新的函数,但必须在函数外面定义这个新函数。
如果在函数内使用的话,函数可以声明为任意类型,如果在另外一个函数中引用新函数的话,新函数必须声明为int类型,否则不能调用。除非另外声明。