需要帮助功能指针在C ++中 [英] Need Help With Functions Pointers In C++

查看:91
本文介绍了需要帮助功能指针在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中有以下代码:

 

#include< stdio.h>

void print()
{
printf(" Hello World\\\
);;
}

int main(int argc,const char * argv [])
{
void(* a)()= print;
void(* b)()=& print;
void(* c)()= * print;
a();
b();
c();

返回0;

}

没有错误和输出是:




Hello World


Hello World


Hello World



我只是想了解并知道我在这段代码中用a,b和c做了什么,以及我是如何将每一个打印出来的。

解决方案

< blockquote>

这是正确的方法:


void(* b)()=& print;


但没有&符号隐式转换为函数指针。


来自标准: (N3376 4.3 / 1)。

函数类型T的左值可以转换为"指向T的指针"的prvalue。结果是指向函数的指针。


There is the following code in C++:

#include <stdio.h> void print() { printf("Hello World\n"); } int main(int argc, const char* argv[]) { void(*a)() = print; void(*b)() = &print; void(*c)() = *print; a(); b(); c();

return 0;

}

There are no errors and the output is:

Hello World

Hello World

Hello World

I just want to understand and know what I have done in this code with a, b and c, and how did I related each one to print.

解决方案

This is the right way:

void(*b)() = &print;

But without the ampersand it gets converted to a function pointer implicitly.

From the standard:  (N3376 4.3/1).

An lvalue of function type T can be converted to a prvalue of type "pointer to T." The result is a pointer to the function.


这篇关于需要帮助功能指针在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆