C++ 回调数组

C++ Array of callbacks

本文关键字:数组 回调 C++      更新时间:2023-10-16

我在 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);

如果你有一个不同的实际问题,那么我建议你用一个新问题重新开始,这是你试图解决的场景的更现实的变体。