如何在这个类中使用函数指针? [英] How do I use function pointers within this class?

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

问题描述

我有一个类:Circle。它可以绘制一个实心圆或一个轮廓的圆。基于它的当前设置,我想要一个draw()方法调用draw_filled()或draw_outlined()。



在我的类中,我有成员 void(* draw)(void);



我有两个私有函数: void draw_filled ); void draw_outlined();



然后,我有以下方法:

  void Circle :: fill(const bool fill)
{
m_fill = fill;

if(fill)
draw = draw_filled;
else
draw = draw_outlined;
}



我在两个绘图赋值中都遇到错误:



错误C2440:'=':无法从'void(__thiscall X2D :: GL :: Circle :: *)(void)'转换为'void(__cdecl *) $ b 1>没有上下文可以进行这种转换



通常情况下,我不在类中使用函数指针,所以这对我来说是新的。任何帮助将不胜感激。谢谢。

解决方案

从错误消息中可以看出 draw 是指向函数的通用指针,而不是指向成员函数的指针。 draw的声明应该是 void(X2D :: GL :: Circle :: * draw)(void),这样 draw 指向 Circle 的成员函数。


I have a class: Circle. It can draw either a filled circle or an outlined circle. Based on its current setting, I want a general draw() method that calls either draw_filled() or draw_outlined().

In my class, I have the member void (*draw)(void);

I have two private functions: void draw_filled(); void draw_outlined();

Then, I have the following method:

void Circle::fill(const bool fill)
{
    m_fill = fill;

    if (fill)
        draw = draw_filled;
    else
        draw = draw_outlined;
}

I get an error on both draw assignments:

error C2440: '=' : cannot convert from 'void (__thiscall X2D::GL::Circle::* )(void)' to 'void (__cdecl *)(void)' 1> There is no context in which this conversion is possible

Normally, I don't use function pointers in classes, so this is new to me. Any help would be appreciated. Thank you.

解决方案

From the error message, it appears that draw is a generic pointer to a function, and not a pointer to a member function. The declaration of draw should be void (X2D::GL::Circle::*draw)(void), so that draw points to a member function of Circle.

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

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