Arduino:指针子类的继承和数组 [英] Arduino: Inheritance and arrays of pointer subclasses

查看:41
本文介绍了Arduino:指针子类的继承和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is problem #2 from this previous question:

Arduino 代码中的继承

根据 Steven 的回答,我确实需要保存指针的数组,以便在其范围之外持久化,这会导致一些奇怪的行为.

Building off of Steven's answer, I do need the array that holds the pointers to persist outside of its scope, which is resulting in some weird behavior.

这是我迄今为止的Board"类,它包含多个子元素:

This is my "Board" class I have so far, that contains multiple child elements:

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();  
}

在我的循环"函数中调用

In my "loop" function I am calling

board.draw(matrix);

这导致写出一些疯狂的串行代码.

which results in some nutty Serial code being written out.

显然我不理解这里类中数组中指针的来龙去脉.

Clearly I am not understanding the ins and outs of pointers in arrays in classes here.

推荐答案

您需要使 Actor::speak 成为虚拟的,编译器对虚拟方法使用动态绑定.

You need to make Actor::speak virtual, the compiler uses dynamic binding for virtual methods.

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

这篇关于Arduino:指针子类的继承和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆