为每个对象定义一个唯一的函数

Defining a unique function for each object

本文关键字:一个 唯一 函数 对象 定义      更新时间:2023-10-16

我有一个类,以及它的对象。如果我想让每个对象都做一些不同的事情,我该怎么办?(也就是说,每个对象都有一个独特的功能)。

以下是我试图实现的目标的简化代码。

基本类

class Thing
{
private:
    int x, y, z;
public:
    static vector<Thing*> objects;
    int getX() {return x;}
    int getY() {return y;}
    int getZ() {return z;}
    Thing(int X, int Y, int Z)
    {
        this->x = X;
        this->y = Y;
        this->z = Z;
        objects.push_back(this);
    }
    void func(); //THE EVENTUAL UNIQUE FUNCTION
};
vector<Thing*> Thing::objects = {};

我的理论所需代码

int main()
{
    Thing A(1, 2, 3);
    void A->func() //A REDEFINITION OF THE PUBLIC FUNCTION
    {
        cout << "do stuff" << endl;
    }
}

使用std::函数和C++11 lambdas

class Thing
{
private:
    int x, y, z;
public:
    static vector<Thing*> objects;
    int getX() {return x;}
    int getY() {return y;}
    int getZ() {return z;}
    Thing(int X, int Y, int Z)
    {
        this->x = X;
        this->y = Y;
        this->z = Z;
        objects.push_back(this);
    }
    std::function<void()> func; //THE EVENTUAL UNIQUE FUNCTION
};

重新定义的独特功能

A.func = [&A]() {  
  // do something
};