数组C++段错误说我有类基类的一个对象:为基类上创建对象
// baseclass.h
class baseclass
{
baseclass() # default constructor, constructs baseclass object
}
而在的.cpp:
// baseclass.cpp
baseclass::baseclass()
{
// member functions and variables
}
现在我的目标是有一个派生类,并且在派生类的默认构造函数中,创建一个静态大小的数组n基类对象。为了澄清,另一种想法是将基类看作扑克牌,我想通过调用派生类的默认构造函数来创建这些卡的数组(卡组)。然而,我决定保留我的问题摘要的范围,所以我会继续使用base/derived,这样其他人可以更容易地看到这可能适用于他们。
我不确定以面向对象的方式设置它的最佳方式,到目前为止我有类似的东西,但我得到了segmentation fault。这是我如何把它设置了:
// derivedclass.h (extending baseclass)
class derivedclass
{
// default constructor for derivedclass object
derivedclass();
// a pointer to an object of type baseclass
baseclass* bar;
// or should it be:
baseclass* bar[n] // where n is an integer
// or is there a better way to do it?
}
最后,因为我说的是一个derivedclass对象可以有一个数组,我必须在的.cpp的默认构造derivedclass是真的:
// derivedclass.cpp
derivedclass::derivedclass()
{
// so I need to initialize the member array
baseclass* bar = new baseclass[n] // where n is the size I want to initialize
// the array to
}
那么,我列出的任何情况会导致分段错误?什么是创建这个对象数组的最佳方式?对不起,如果这是一个不好的问题,我仍然是一个学习很多关于内存分配和指针的学生,通常处理语言,我不必担心这一点。另外,我试图将问题摘要保留为其他人的利益。提前致谢!
如果你知道它将在编译时的大小,使用'std :: array'。如果没有,使用'std :: vector'。你也** **你的数据成员在构造函数中。 – chris