C++ 稍后在c+中实现一个通用方法+;

C++ 稍后在c+中实现一个通用方法+;,c++,C++,我知道下面的代码不会编译,但我还是发布了它,因为它是我试图实现的示例 typedef struct { void actionMethod(); }Object; Object myObject; void myObject.actionMethod() { // do something; } Object anotherObject; void anotherObject.actionMethod() { // do something else; } ma

我知道下面的代码不会编译,但我还是发布了它,因为它是我试图实现的示例

typedef struct {
    void actionMethod();
}Object;

Object myObject;

void myObject.actionMethod() {
    // do something;
}

Object anotherObject;

void anotherObject.actionMethod() {
    // do something else;
}

main() {
    myObject.actionMethod();
    anotherObject.actionMethod();
}
基本上我想要的是某种委托。有什么简单的方法可以做到这一点吗

我也不能包含
标题并使用
std::function
。我如何才能做到这一点?

例如:

#include <iostream>

using namespace std;

struct AnObject {
    void (*actionMethod)();
};

void anActionMethod() {
    cout << "This is one implementation" << endl;
}

void anotherActionMethod() {
    cout << "This is another implementation" << endl;
}

int main() {
    AnObject myObject, anotherObject;
    myObject.actionMethod = &anActionMethod;
    anotherObject.actionMethod = &anotherActionMethod;

    myObject.actionMethod();
    anotherObject.actionMethod();

    return 0;
}

对象
一个函数指针成员:

struct Object {
    void (*actionMethod)();
};
在这里,成员
actionMethod
是指向不带参数也不返回任何内容的函数的指针。然后,假设您有一个名为
foo
的函数,您可以将
actionMethod
设置为指向该函数,如下所示:

Object myObject;
myObject.actionMethod = &foo;

然后可以使用
myObject.actionmethod()

调用它,您可以让对象存储函数指针。
Object myObject;
myObject.actionMethod = &foo;