使用类继承和malloc(在arduino上)
Using class inheritance and malloc (on an arduino)
这个问题也出现在正常的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的建议使用"放置新"语法(另见这里)。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 如果没有malloc,链表实现将失败
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- malloc() 可能出现内存泄漏
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 人脸跟踪arduino代码的优化
- vscode下的Arduino代码出现意外编译错误
- Arduino从Txt读取整数
- Arduino C++在构造函数中用参数声明对象数组
- C++ Boost::asio串行通信与Arduino无法写入
- 当我尝试加载内核模块时,如何修复C++中的这个 malloc() 错误?
- Arduino millis() - millis() 怎么能等于 0 以外的任何东西?
- 在Arduino中将PWM通道命名为LEDC是否有特定原因
- 'val' Arduino 错误代码之前的预期'('
- 在C++中创建队列 - 什么是 malloc 错误?
- 我可以在 Arduino 的库文件夹之外安装库吗?
- 如何在 malloc 内存中初始化非 POD 数据
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 使用类继承和malloc(在arduino上)