Arduino:指针子类的继承和数组

Arduino: Inheritance and arrays of pointer subclasses

本文关键字:继承 数组 子类 指针 Arduino      更新时间:2023-10-16

这是上一个问题的第2个问题:

Arduino代码中的继承

在Steven的回答的基础上,我确实需要一个数组来保持指针在其范围之外,这会导致一些奇怪的行为。

到目前为止,这是我的"Board"类,它包含多个子元素:

Board.h:

#ifndef Board_h
#define Board_h
#include <StandardCplusplus.h>
#include <serstream>
#include <string>
#include <vector>
#include <iterator>
#include "Arduino.h"
#include "Marble.h"
#include "Wall.h"
class Board
{
  public:
    Board();
    void draw(double* matrix);
  private:
    Marble marble;
    //std::vector<Actor> children;
    Actor* children[2];
};
#endif

Board.cpp:

#include "Arduino.h"
#include "Board.h"
#include <math.h>
#include <iterator>
#include <vector>
Board::Board()
{
}
void Board::create(double* _matrix, int _cols, int _rows) {
  Marble *marble = new Marble();
  Wall wall;
  children[0] = marble; 
  //children.push_back(marble);
  //children.push_back(wall);

}

void Board::draw(double* matrix) {
  Serial.println("board draw");
  children[0]->speak();  
}

在我的"循环"功能中,我调用

board.draw(matrix);

这导致了一些疯狂的串行代码被写出。

很明显,我不理解类中数组中指针的来龙去脉。

您需要使Actor::speak虚拟化,编译器对虚拟方法使用动态绑定。

class Actor
{
  public:
    Actor();
    virtual void speak();  // virtual
  private:
};