繁体   English   中英

创建对象数组时的 C++ 分段错误

[英]C++ Segmentation fault on creating an array of objects

假设我有一个类基类的对象:

// baseclass.h
class baseclass
{
    baseclass() # default constructor, constructs baseclass object
}

在基类的 .cpp 中:

// baseclass.cpp
baseclass::baseclass()
{
    // member functions and variables
}

现在我的目标是拥有一个派生类,并在派生类的默认构造函数中,创建一个静态大小为n 个基类对象的数组。 为了尝试澄清,另一种思考方式是将基类视为扑克牌,我想通过调用派生类的默认构造函数来创建这些牌的数组(一副牌)。 但是,我决定将我的问题的范围保持抽象,因此我将继续使用 base/derived,以便其他人可以更轻松地了解这如何适用于他们。

我不确定以面向对象的方式设置它的最佳方法,到目前为止我有这样的东西,但我遇到了一个段错误 这是我如何设置它:

// 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?
}

最后,因为我说派生类对象可以有一个数组,所以我必须为派生类的 .cpp 中的默认构造函数做到这一点:

// 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
}

那么我列出的任何情况都会导致分段错误吗? 创建此对象数组的最佳方法是什么? 对不起,如果这是一个菜鸟问题,我是一名学生,仍在学习很多关于内存分配和指针的知识,通常处理我不必担心的语言。 此外,为了他人的利益,我试图使问题保持​​抽象。 提前致谢!

我不知道为什么你需要在这里使用动态分配。 我宁愿做这样的事情,这也会为您节省一些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;
};
// so I need to initialize the member array
baseclass *bar = new baseclass[n];

除此之外,你不初始化成员数组,只初始化一个与成员变量同名的局部变量,因此它隐藏它(出于同样的原因,你也通过丢失指针来泄漏内存到new分配的数组)。

为什么要使用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
 };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM