当前位置: 动力学知识库 > 问答 > 编程问答 >

dependency injection in Arduino

问题描述:

I've started working with Arduino and I want to do a time share system so I do not use the delay command.

I have a problem when I try to register objects that inherit from another.

Here I have a test code that should show in the terminal: "Wow wow Miuau miuau ..."

I have doubts when I try to create an Interface and how do I declare the register () function so that Cat and Dog objects can be entered in the Animal type Array.

The following code is only to show the problem:

class Animal {

public:

void message() {

}

};

class Dog : public Animal {

public:

void message() {

Serial.println("Guau guau");

}

};

class Cat : public Animal {

public:

void message() {

Serial.println("Miau miau ");

}

};

class Multiplex {

private:

int index = 0;

Animal objects[5];

public:

void register(Animal object) {

objects[index] = object;

index++;

}

void go() {

for(int i = 0;i<index;i++) {

objects[i].message();

}

}

};

Dog dog;

Cat cat;

Multiplex multiplex;

void setup() {

// put your setup code here, to run once:

Serial.begin(9600);

multiplex.register(dog);

multiplex.register(cat);

}

void loop() {

// put your main code here, to run repeatedly:

multiplex.go();

delay(1000);

}

Any help is welcome ...

Thanks and sorry for my english.

网友答案:

In this case you have to use polymorphism (virtual methods). But it still won't work with so many copies of "registered" object into the Animal base class (it shows nothing because Animal::message() is called). You have to use pointers (or references - but it's not so easy in this case)

class Animal { // pure virtual class (abstract class)
  public:
    virtual void message() = 0; // The '= 0;' makes whole class "pure virtual"
 };

class Dog : public Animal {
  public:
  virtual void message() {
    Serial.println("Guau guau");
  }
};

class Cat : public Animal {
  public:
  virtual void message() {
    Serial.println("Miau miau ");
  }
};

class Multiplex {
  private:
    int index = 0;
    Animal * objects[5];
  public:

  void reg(Animal * object) { // pass pointer to the object
    objects[index] = object;  // object must be valid for whole time
    index++;
  }

  void go() {
    for(int i = 0;i<index;i++) {
      objects[i]->message();
    }
  }

};

Dog dog;
Cat cat;
Multiplex multiplex;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  multiplex.reg(&dog);
  multiplex.reg(&cat);

}

void loop() {
  // put your main code here, to run repeatedly:
  multiplex.go();
  delay(1000);
}

If you don't like dynamic polymorphism, you have to use something like object type, switch and typecasting to its correct type.

分享给朋友:
您可能感兴趣的文章:
随机阅读: