动态内存请求导致错误的是什么?

时间:2013-07-18 15:13:56

标签: c++ class memory

class tower {
public:
    unsigned int no;             // ERROR!
    int *levels = new int[no];   // the error disappears when I comment out this line
    tower(int init) {no = init;}    
};

我在上面做了类声明,但出于某种原因,它不起作用。显示的错误消息是:无效使用非静态数据成员'tower :: no'。为什么?我真的不确定发生了什么。

有人可以帮忙吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

class tower {
public:
    unsigned int no;
    int *levels;
    tower(int init) { no = init; levels = new int[no]; }    
};

编辑如果不明显,“水平”的初始化会在初始化“否”后移动。您必须在“否”之后初始化“级别”,因为“new int [no]”将无法正确执行,直到“no”具有值。

答案 1 :(得分:0)

在Tower.h:

class Tower 
{
public:
    Tower(int size);  // Note that we're missing a destructor which 
                      // should invoke delete[] on _levels.
    unsigned int _size;
    int *_levels;  // Consider some sort of smart pointer 
                   // later when as you continue to learn C++, 
                   // or use std::vector!
};

在Tower.cpp中:

Tower::Tower(int size) : _size(size), _levels(NULL)
{
    if(_size > 0)
    {
        _levels = new int[size];
    }
}

查看examples online too

答案 2 :(得分:0)

编译器试图告诉您,您正在无效使用非静态成员。这意味着“no”的值在构造函数的某个时间之前不会具体。

只看你自己的构造函数实现:

tower(int init /*future value of no)
    // <-- this is where initialization is done by the compiler,
    // so the compiler would be trying to do
    // : m_init(new int[no]).
    // What value does "no" have right now?
{
    no = init;  // <-- you are going to assignment rather than initialization.
}

执行此操作的正确方法是使用初始化列表。

class Tower
{
    int m_no;
    int* m_levels;
publc:
    Tower(int no_)
        : m_no(no_)
        , m_levels(no_ ? new int[no_] : nullptr)
    {
    }
};