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

问题描述

这是问题#2从这个previous问题:

This is problem #2 from this previous question:

建筑了史蒂芬的答案,确实需要一个保存指向它的范围,这是导致一些怪异的行为之外坚持的数组。

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.

这是我的局级我到目前为止,包含多个子元素:

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:

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

这导致一些坚果串行code

被写入了。

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.

推荐答案

您需要让演员::说话虚拟,编译器使用动态虚拟方法结合。

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的:继承和子类的指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:33