0

我知道下面的代码不会编译,但我还是发布了它,因为它体现了我想要完成的事情。

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();
}

基本上我想要的是某种代表。有一些简单的方法可以做到这一点吗?

我不能包含<functional>标题并使用std::function任何一个。我怎样才能做到这一点?

4

2 回答 2

1

例如:

#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;
}

输出:

This is one implementation 
This is another implementation
于 2013-05-19T19:57:30.313 回答
1

Object一个函数指针成员:

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

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

Object myObject;
myObject.actionMethod = &foo;

然后您可以使用myObject.actionmethod().

于 2013-05-19T19:57:47.793 回答