为每个对象定义一个唯一的函数
Defining a unique function for each object
我有一个类,以及它的对象。如果我想让每个对象都做一些不同的事情,我该怎么办?(也就是说,每个对象都有一个独特的功能)。
以下是我试图实现的目标的简化代码。
基本类
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
};
相关文章:
- c++多进程编写一个唯一的文件
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 从另一个唯一 ptr 的原始 ptr 创建唯一的 ptr
- 如何在以 256 为基数的唯一 xLen-digit 表示中写一个整数 x?
- 需要在C 中生成一个从00001到99999的唯一5位数字
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- 尝试创建一个读取.txt文件,显示它,计数唯一单词的程序,并在使用了多少次的情况下显示独特的单词.C
- 如何制作一个采用类型类的唯一指针?(通用)它不让我
- 为什么要在 c++ 中创建一个指向基元类型的唯一指针?
- 如何将唯一指针从一个向量移动到另一个唯一指针向量
- 将 n 个整数组合成一个唯一的表示形式
- 正确地返回一个唯一的ptr
- 为每个对象定义一个唯一的函数
- 需要在数组中找到一个唯一的数字
- 更快的方式,然后我填充一个唯一的整数除了两个值的向量?c++
- 如何将三个整数组合成一个唯一的标记,使标记在c++中保持整数
- 一个唯一的ptr类如何将它的实例指针传递给它的成员对象
- 试图在每次迭代中产生一个唯一的随机数序列
- 可变模板类:每个可变模板参数可以实现一个唯一的成员函数吗
- 如何将两个正整数映射为一个唯一的整数