C++中函数中声明函数的问题—————我也诡异了一把

        话说在C/C++语言中,不能在一个函数里面定义另外一个函数,但是没有说不可以声明,于是就声明了一个试试。


  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.     int fun();
  6.     cout<<"hahah"<<endl;
  7.     fun();
  8.     return 0;
  9. }
  10. int fun()
  11. {
  12.     cout<<"this int int itn fun"<<endl;
  13. }

 


        但是有什么意义呢?它与下面这段函数的意义是相同的。至少在表面上是这样:


  1. #include <iostream>
  2. using namespace std;
  3. int fun();
  4. int main()
  5. {
  6.     cout<<"hahah"<<endl;
  7.     fun();
  8.     return 0;
  9. }
  10. int fun()
  11. {
  12.     cout<<"this int int itn fun"<<endl;
  13. }

             但是想想,这与在函数外部声明函数有什么区别呢?这个体现出了C与C++的区别。
先看C代码:

  1. #include <stdio.h>
  2. void aprintfun()
  3. {
  4.     printf("this is in the function aprintfun/n");
  5.     fun();
  6. }
  7. int main()
  8. {
  9.     int fun();
  10.     fun();
  11.     printf("hahahah,this is a funny test/n");
  12.     aprintfun();
  13.     return 0;
  14. }
  15. int fun()
  16. {
  17.     printf("this is in the fun function/n");
  18. }

             只有在函数定义为int类型的时候才可以这样用,定义为void不行,定义为double也不行。
             而对于C++,这样用是完全行不通的,试过把函数定义为int,定义为void,都不行,提示出错:
                       error:fun was not declared in this scope
代码如下:

  1. #include <iostream>
  2. using namespace std;
  3. void aprintfun()
  4. {
  5.     cout<<"aprintfun/n";
  6.     fun();
  7. }
  8. int main()
  9. {
  10.     void fun();
  11.     cout<<"hahah"<<endl;
  12.     fun();
  13.     aprintfun();
  14.     return 0;
  15. }
  16. void fun()
  17. {
  18.     cout<<"this int int itn fun"<<endl;
  19. }

             综合上面所说,在C++中,可以在一个函数里面声明一个新的函数,但是只能在这个函数内使用这个新的函数,新函数的定义一定在放在这个函数的外面。
             如果想在另外的一个函数中用新函数的话,是不可以的,除非再声明一个。
             在C语言中,可以在一个函数里面声明一个新的函数,但必须在函数外面定义这个新函数。
             如果在函数内使用的话,函数可以声明为任意类型,如果在另外一个函数中引用新函数的话,新函数必须声明为int类型,否则不能调用。除非另外声明。
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值