我使用以下代码得到了分段错误,我真的不知道这里发生了什么。它似乎与Master-class中的指针有关,但我不知道如何解决这个问题。我有以下代码:
class Shape
{
public:
Shape(){}
~Shape(){}
virtual void draw() = 0;
};
class Circle : public Shape
{
public:
Circle(){}
~Circle(){}
void draw()
{
printf("circle");
// code for drawing circle
}
};
class Line : public Shape
{
public:
Line() {}
~Line() {}
void draw()
{
printf("line");
// code for drawing line
}
};
class Master
{
public:
Shape* member_shape;
public:
Master()
{}
~Master()
{}
void add_shape_circle()
{
member_shape = new Circle();
}
void add_shape_line()
{
member_shape = new Line();
}
};
Master* master_object;
您是否知道如何使此代码正常工作?感谢。
编辑(添加主要功能):
实际上我的代码中没有像下面这样的主函数,因为我在MATLAB c-mex函数中使用了代码。但它应该是这样的:
//... classes from above here
int main()
{
master_object = new Master();
master_object->add_shape_circle();
master_object->member_shape->draw(); // segmentation error here
return 0;
}
如果我在Circle
- 构造函数中直接实例化Master
对象,则不会发生错误。但是,无法在Line
和Circle
之间进行选择。示例:如果我将Master
类更改为以下内容,则函数调用master_object->member_shape->draw()
不会导致错误。
class Master
{
public:
Shape* member_shape;
public:
Master()
{
member_shape = new Circle();
}
~Master()
{}
void add_shape_circle(){}
void add_shape_line(){}
};
所以,这个未初始化的指针有一些东西......我想。
答案 0 :(得分:1)
该问题可能与您使用printf
有关。来自https://www.mathworks.com/help/matlab/matlab_external/creating-c-mex-files.html?requestedDomain=www.mathworks.com:
使用cout或C语言printf函数在C ++ MEX文件中无法正常工作。请改用mexPrintf函数。