使用类继承和malloc(在arduino上)

Using class inheritance and malloc (on an arduino)

本文关键字:arduino malloc 继承      更新时间:2023-10-16

这个问题也出现在正常的C++代码中,但这不是问题,因为在正常的C++中,我可以使用"new"而不是"malloc"。

我想做的是制作一个具有相同接口但不同函数和成员变量的对象链表,并希望使用虚拟类的成员来做到这一点。

但是我遇到了细分错误。我首先在Arduino C++中制作了以下简单的示例代码(基于此):

class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area (void) =0;
    void printarea (void)
      { Serial.println( this->area() ); }
  };
class CRectangle: public CPolygon {
  public:
    int area (void)
      { return (width * height); }
  };

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}
void loop() {
  CRectangle rect;
  CPolygon * ppoly1 = ▭
  ppoly1->set_values (4,5);
  ppoly1->printarea();
  delay(1000);
}

我也在正常C++中做到了,希望找到错误(它只是给了我一个分割错误):

#include <iostream>
#include <stdlib.h>
using namespace std;
class CPolygon {
  protected:
    int width, height;
  public:
    void set_values (int a, int b)
      { width=a; height=b; }
    virtual int area (void) =0;
    void printarea (void)
      { cout << this->area() << endl; }
  };
class CRectangle: public CPolygon {
  public:
    int area (void)
      { return (width * height); }
  };

int main () {
  CRectangle * rect;
  rect = (CRectangle*) malloc(sizeof(CRectangle));
  * rect = CRectangle();
  CPolygon * ppoly1 = rect;
  ppoly1->set_values (4,5);
  ppoly1->printarea();
  return 0;
}

就像我说的,我使用新的尝试了这个:

int main () {
  CRectangle * rect;
  rect = new CRectangle;
  CPolygon * ppoly1 = rect;
  ppoly1->set_values (4,5);
  ppoly1->printarea();
  return 0;
}

这工作正常。

我真的不确定在我的调试过程中从这里开始。我做错了什么,还是这是 malloc() 的固有限制,因此也是 arv-g++ 的固有限制?

要使用通过 malloc 保留的空间,您可以执行以下操作:

new(rect) CRectangle();

而不是

* rect = CRectangle();

当我找到使用该语法的引用时,我会把它写在这里。

我同意C++版本与新作品很好。 这是因为 new 为类的实例分配内存,然后调用构造函数。 malloc 不这样做,它只是分配内存,因此类从未正确形成,这就是 malloc 版本崩溃的原因。始终对类使用新建和删除。

我真的不确定在我的调试过程中从这里开始。我做错了什么,还是这是 malloc() 的固有限制,因此也是 arv-g++ 的固有限制?

的,此限制是malloc()固有的(这是 C 而不是 C++ BTW)。若要实例化类对象C++,必须调用它们的构造函数方法之一以正确初始化分配的内存,而malloc()不会提供。

我对 arduino 没有经验,但如果操作系统已经支持 malloc() 用于动态内存分配,那么也应该支持new。至少你可以按照Martin Lavoie的建议使用"放置新"语法(另见这里)。