C++ 回调数组
C++ Array of callbacks
我在 c++ 中创建回调向量时遇到了一些麻烦。我有一个接口,其中包含一个函数和 2 个实现该接口的类。我想从程序其他部分的向量调用此函数。
我只需要那个函数,所以我不想存储指向整个对象的指针
下面是我想做的一个简单的例子:
#include <iostream>
#include <vector>
class IAnimal{
public:
IAnimal(){};
~IAnimal(){};
virtual void eat(int,int) = 0;
};
class Dog: public IAnimal{
public:
Dog(){};
~Dog(){};
virtual void eat(int food, int water){
std::cout<<"Dog: " << food<< " " << water << std::endl;
}
};
class Cat :public IAnimal{
public:
Cat(){};
~Cat(){};
virtual void eat(int food, int water){
std::cout << "Cat: " << food << " " << water << std::endl;
}
};
class Test{
private:
std::vector<void (IAnimal::*)(int, int)> vec;
public:
void Init(){
IAnimal* dog1 = new Dog();
IAnimal* dog2 = new Dog();
IAnimal* cat3 = new Cat();
//here I want to add callbacks to vec
void(IAnimal::*f)(int, int) = &IAnimal::eat;
(*f)->dog1.eat;//doesn't work
vec.push_back(f);
}
void RunTest(){
for (int i = 0; i < vec.size(); i++)
{
//here I call the callbacks
vec[i](i, i);//also I don't know how this should be called
}
}
};
void main(){
Test t;
t.Init();
t.RunTest();
getchar();
}
当你有多态性并使用虚函数时,你需要一个对象。所以你的代码:
void RunTest(){
for (int i = 0; i < vec.size(); i++)
{
//here I call the callbacks
vec[i](i, i);//also I don't know how this should be called
}
}
不起作用,因为您传递给回调的 OBJECT 丢失了。因此,尽管这可能会调用 eat
函数,但它没有作为隐藏参数传递的动物对象。因此,此代码永远不会按编写的方式工作。
从技术上讲,通过函数指针调用虚函数是可能的,但通常我会说这是一种"难闻的气味"(换句话说,是糟糕代码的标志)。
我对所描述问题的建议是使用std::vector<IAnimal*> vec;
,然后使用vec[i]->eat(i, i);
。
如果你有一个不同的实际问题,那么我建议你用一个新问题重新开始,这是你试图解决的场景的更现实的变体。
相关文章:
- C++向数组添加元素并调整数组大小
- c ++数据输入并读回列表中的结构结构中的数组
- 从数组调用字段
- 整数数组中最长的回文
- 如何在c++中将字节数组转换回jpeg
- 转换回二维数组
- 将数组传递回主体
- 代码不会打印回 numSum 作为 numSum = 数组中的 2 个点
- 将稀疏数组从 matlab 传递到 Eigen (C++),然后再传递回 matlab
- void 函数将数组发送回 main,但我无法让数组正确输出值
- 如何编写一个 void 函数,该函数将在数组中搜索值,并通过引用将该值的位置传递回 main 函数
- 当函数调用时,试图阻止数组更改时发生无效转换错误
- 将数组值从函数传递回结构
- 你如何打印出使用数组删除某些字符的回文
- 使用数组的 C++ 回文程序
- 无限数组C++在一个表达式中使用两个新值调整数组大小
- C++整数数组回文检查器
- 通过初始化列表或变量推回结构的数组
- 检查子数组是否为带指针的回文数组
- C++ 回调数组