Arduino:指针子类的继承和数组
Arduino: Inheritance and arrays of pointer subclasses
这是上一个问题的第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:
};
相关文章:
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 如何从 c++ 中类中内置的数组继承
- 从 std::数组私下继承时无法从 std::initializer_list 构造
- 删除C++中的继承类指针数组
- 继承向量/数组/列表并更改其大小
- 复制构造函数继承动态分配的数组
- 继承类的数组
- C++数组继承中的对象
- 继承构造函数不允许类似数组的初始化
- 在C++中扩展继承的数组
- 如何在C++中构建一个对象数组,这些对象都继承自一个主类
- C++类扩展(继承类中数组的不同大小)
- 指向从 1 个基类继承的不同类对象的指针数组
- 动态数组和类继承
- 继承和指针数组
- 有没有办法在继承类的基类中指定数组的大小
- 如何使数组包含从基类继承的类
- 不更新数组的继承机器人竞赛
- 有没有办法放入一个未定义大小的数组并作为静态数组继承
- 在函数中传递继承的类数组会导致内存泄漏