C ++遍历成员函数

时间:2018-10-10 09:40:25

标签: c++ pointers microcontroller

我有一个设计问题:

我有一个描述机器人的课程;它可以向不同的方向移动,也可以将相机移动到不同的视图等。

class Robot {
    private:
        ...

    public:
        void move_right();
        void move_left();
        void switch_camera()
        void raise_camera()
}

我想添加另一个执行一系列事件的方法。问题是,我需要中途终止事件。

我确实想澄清一下,该机器人是在微控制器上运行的,而不是在标准操作系统上运行的-因此,我无法真正将信号发送到进程或其他任何东西。

我的第一个想法是将事件函数存储在数组中并对其进行迭代:

#typedef void(robo_event *)(void)

robo_event next_event;
robo_event *event_sequence;

Robot() {
    this->next_event = nullptr;

}


void perform_event_series() {
    for(this->next_event = *event_sequence; this->next_event != nullptr; this->next_event+=sizeof(robo_event)) {
        this->next_event();
    }
}

void abort_event_series() {
    this->next_event = nullptr;
}

事实是,c ++标准禁止存储成员函数的地址,因此这开始变得尴尬。我可以使这些函数静态化,但是我确实需要经常使用它们,但这仍然很尴尬。我希望能够在没有更改的情况下更改事件序列而无需进行过多工作,因此我认为最好将它们保存在某种数组/向量中。

任何对c ++成员函数语法的帮助/关于如何解决此问题的更好的主意,将不胜感激。

3 个答案:

答案 0 :(得分:2)

Thing is, the c++ standard forbids storing addresses of member functions

C++ most certainly allows you to store pointers to member functions (and variables), but the syntax is a bit different to accommodate the this pointer type, virtual functions, inheritance, etc.

class Example
{
public:
    double foo(int x) { return x * 1.5; }
};
int main() {
    double (Example::* member_function_ptr)(int);
    member_function_ptr = &Example::foo;

    Example example;
    std::cout << (example.*member_function_ptr)(2) << std::endl;
}

If all your functions are for the same class, same return type, same arguments, etc. then you can make a table of them easy enough.

答案 1 :(得分:1)

函数指针的类型与成员指针的类型不同。

您需要void(Robot::*)(void)而不是void(*)(void)

class Robot {
private:
    typedef void(Robot::*robot_event)(void)

    robo_event next_event;
    robo_event *event_sequence;

    Robot() {
        next_event = nullptr;

    } 

    void perform_event_series() {
        for(next_event = *event_sequence; next_event != nullptr; ++next_event) {
            (this->*next_event)();
        }
    }

    void abort_event_series() {
        next_event = nullptr;
    }

public:
    void move_right();
    void move_left();
    void switch_camera()
    void raise_camera()

}

答案 2 :(得分:1)

在c ++中完全允许存储指向成员函数的指针:

public sealed class Singleton
{
    private static WeakReference<Singleton> weakInstance;

    public WeakReference<Singleton> Instance
    {
        get
        {
            if (weakInstance == null)
                weakInstance = new WeakReference<Singleton>(this);
            else
                weakInstance.SetTarget(this);
            return weakInstance;
        }
    }
}
相关问题