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

implement a general method later in c++

本文关键字:一个 方法 c++ 实现      更新时间:2023-10-16

我知道下面的代码无法编译,但我还是把它贴出来了,因为它说明了我想要完成的任务。

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。我该怎么做呢?

例如:

#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

Object一个函数指针成员:

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

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

Object myObject;
myObject.actionMethod = &foo;

可以用myObject.actionmethod()调用