【发布时间】:2013-09-12 21:05:50
【问题描述】:
这个问题也出现在普通的 C++ 代码中,但这不是问题,因为在普通的 C++ 中我可以使用“new”而不是“malloc”。
我想做的是创建一个具有相同接口但函数和成员变量不同的对象的链接列表,并希望使用虚拟类的成员来做到这一点。
但是我遇到了分段错误。我首先在 Arduino C++ 中制作了以下简单示例代码(基于this):
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;
}
就像我说的,我用 new 试过这个:
int main () {
CRectangle * rect;
rect = new CRectangle;
CPolygon * ppoly1 = rect;
ppoly1->set_values (4,5);
ppoly1->printarea();
return 0;
}
而且效果很好。
我不太确定在调试过程中该从哪里开始。我做错了什么,还是这是 malloc() 的固有限制,因此也是 arv-g++ 的限制?
【问题讨论】:
-
'普通 C++' 到底是什么意思?如果你有一个 C++ 编译器并且你有一个支持
malloc()的 stdlib 实现,new在 C++ 代码中应该可以正常工作。如果您将new与您的 arduino 交叉工具链一起使用会发生什么? -
malloc()永远不会适用于这个 BTW,因为除了内存分配之外,您还需要正确构造(初始化)类实例。 -
我正在为 arduino 编程,所以我需要使用 arv-g++ 编译器。我在某处读到该编译器不支持 new 和 delete,只支持 malloc 和相关函数,所以我从没想过尝试。显然,arduino 的人在他们的库中添加了支持,我从没想过要尝试......
-
通常它正在沸腾以提供适当的 stdc++ 库存根。 GCC(听起来是这个工具链的基础)使用 newlib 和它的 stdc++ 库实现。一些 newlib 存根需要针对实际的操作系统环境进行定制。
-
我一直在使用 new 和 delete for arduino(使用标准的 arduino IDE),完全没有问题。它的工作原理与 Visual Studio、xcode 等中的完全一样。