账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    C++ 与 C 中的函数指针
    32
    0

    相关代码

    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>
    
    void *print_message_function( void *ptr );
    
    main()
    {
         pthread_t thread1, thread2;
         const char *message1 = "Thread 1";
         const char *message2 = "Thread 2";
         int  iret1, iret2;
    
         iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
         if(iret1)
         {
             fprintf(stderr,"Error - pthread_create() return code: %d\n",iret1);
             exit(EXIT_FAILURE);
         }
    
         iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
         if(iret2)
         {
             fprintf(stderr,"Error - pthread_create() return code: %d\n",iret2);
             exit(EXIT_FAILURE);
         }
    
         printf("pthread_create() for thread 1 returns: %d\n",iret1);
         printf("pthread_create() for thread 2 returns: %d\n",iret2);
    
         pthread_join( thread1, NULL);
         pthread_join( thread2, NULL); 
    
         exit(EXIT_SUCCESS);
    }
    
    void *print_message_function( void *ptr )
    {
         char *message;
         message = (char *) ptr;
         printf("%s \n", message);
    }
    

    疑惑地方

    在函数 pthread_create(pthread_t * thread, const pthread_attr_t * attr,void * (*start_routine)(void *), void *arg);
    其中 void * (*start_routine)(void *) 这个参数是 "函数指针"
    而根据函数 void *print_message_function( void *ptr );原型来看这是一个 返回任何指针类型的函数,不是函数指针,而且这个函数的实现中并没有返回值. 但是可以使用gcc编译通过,没有任何异常, 有哪位知道这是为什么吗? 或者给出一个参考链接?

    我所知道的类似void *print_message_function( void *ptr ); 函数的用法是这样的

    
     #include<stdio.h>
    
     void *test_f(int *n);
     
     int main(void) 
    {
             int test_num = 32;
             int *test_p = &test_num;
             int *ret_v = test_f(test_p);
             printf("%d \n",*ret_v);
             return 0;
     }
    
    void *test_f(int *n) 
    {
             *n = *n + 1;
             return n;
    }
    
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 锻己 普通会员 1楼

      在C++中,函数指针是一种特殊的指针,它指向一个函数的地址。函数指针可以用来执行函数,而不需要创建和销毁对象。

      函数指针可以是函数的地址,也可以是函数指针的引用。函数指针通常用于传递函数的引用,或者在需要调用函数的地方作为参数传递。

      函数指针在C++中被广泛使用,因为它提供了更灵活的编程方式。函数指针可以用来实现面向对象编程,也可以用来实现函数式编程。

      以下是一个简单的函数指针的例子:

      ```cpp

      include

      // 定义一个函数 void myFunction(int x) { std::cout << "This is my function." << std::endl; }

      int main() { // 创建一个函数指针 int (*funcPtr)(int);

      // 将函数指针赋值给变量
      funcPtr = &myFunction;
      
      // 使用函数指针调用函数
      (*funcPtr)(5) // 输出:This is my function.
      
      return 0;
      

      } ```

      在这个例子中,我们首先定义了一个函数myFunction,然后在main函数中,我们创建了一个函数指针funcPtr,并将其赋值给变量。然后,我们使用函数指针调用myFunction函数,输出This is my function.

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部