访问类中的函数指针 [英] Accessing function pointer inside class

查看:173
本文介绍了访问类中的函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类中定义函数指针,并试图通过类的实例访问它,但它显示一个错误。

I am defining function pointer inside a class and trying to access it through an instance of the class but it shows an error.

这里是代码: p>

Here is the code:

 1 #include<stdio.h>
 2 
 3 class pointer {
 4 public:
 5    int (pointer::*funcPtr)(int);
 6    pointer() {
 7       funcPtr = &pointer::check;
 8    }
 9 
10 
11    int check(int a)
12    {
13       return 0;
14    }
15 
16 };
17 
18 int main()
19 {
20    pointer *pt=new pointer;
21    return (pt->*funcPtr)(3);
22 }

显示编译时错误:

checkPointer.cpp:21:15: error: ‘funcPtr’ was not declared in this scope

请帮助我。

提前感谢。

推荐答案

这里的问题是funcPtr在pt中声明,所以你需要使用名称pt两次 - 一次作为指针指向成员的左侧,选择,并且一次选择从其中选择funcPtr的指针类:

The issue here is that funcPtr is declared inside of pt, so you need to use the name pt twice - once as the left-hand side of the pointer-to-member-selection, and once to choose the pointer class from which to select funcPtr:

(fn->*(fn->funcPtr))(3);

这样做的原因是你可能调用一个实例的funcPtr成员指向的函数

The reason for this is that you could potentially call the function pointed at by the funcPtr member of one instance of pointer on another instance of pointer.

希望这有助于!

这篇关于访问类中的函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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