2013-03-28 89 views
0

数组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 
} 

那么,我列出的任何情况会导致分段错误?什么是创建这个对象数组的最佳方式?对不起,如果这是一个不好的问题,我仍然是一个学习很多关于内存分配和指针的学生,通常处理语言,我不必担心这一点。另外,我试图将问题摘要保留为其他人的利益。提前致谢!

+0

如果你知道它将在编译时的大小,使用'std :: array'。如果没有,使用'std :: vector'。你也** **你的数据成员在构造函数中。 – chris

回答

1
// so I need to initialize the member array 
baseclass *bar = new baseclass[n]; 

除了这个,你不初始化成员数组,只有一个局部变量具有相同的名称作为成员变量,因此它阴影(以及同样的原因,你通过丢失指向new ly分配数组的指针也泄漏内存)。

+1

'<! - 在下面插入注释关于使用std :: vector的注释 - >' – 2013-03-28 19:36:31

3

我不知道为什么你需要在这里使用动态分配。我宁愿做这样的事情,这也将节省您在derivedclass的构造一些工作:

struct baseclass 
{ 
    // Stuff... 
}; 

struct derivedclass : baseclass 
{ 
    // Stuff... 

    baseclass objects[N]; 
}; 

在C++ 11,你应该使用std::array<>,而不是一个普通的C数组(std::array<>是一种安全,一个C数组的零开销包装):

// ... 

#include <array> 

struct derivedclass : baseclass 
{ 
    // Stuff... 

    std::array<baseclass, 10> objects; 
}; 
1

为什么使用new呢?为什么要从卡片派生卡片?甲板上含有卡片。

class Card 
{ 
    // ... whatever card does 
}; 

class Deck 
{ 
public: 
    static int const CountOfCards = 36; 
    typedef std::array<Card,CountOfCards> Cards; 
    Cards cards; 
    // etc. ... whatever deck does 
};