在类中初始化可变大小的数组 [英] initializing array of variable size inside a class

查看:24
本文介绍了在类中初始化可变大小的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据构造函数的输入参数初始化一个大小为 n 的数组.这有效:

I am trying to initialize an array of size n based off the input argument of my constructor. This works:

//Inside Header
class runningAverage{
    private:
        byte n;
        float array[10];
    public:
        runningAverage(byte);
};

//Inside .cpp
runningAverage::runningAverage(byte a){
    n = a;
    for (byte i = 0; i<n; i++) {
        array[i] = 0;
    }
}

这不起作用:

//Inside Header
class runningAverage{
    private:
        byte n;
        float array[];
    public:
        runningAverage(byte);
};

//Inside .cpp
runningAverage::runningAverage(byte a){
    n = a;
    for (byte i = 0; i<n; i++) {
        array[i] = 0;
    }
}

我想初始化数组,使其成为 n 指定的大小.这样我就不会通过任意指定 float array[256] 或类似的东西来浪费内存.任何帮助表示赞赏!

I want to initialize the array so that is the size specified by n. This way I don't waste memory by arbitrarily specifying float array[256] or something like that. Any help is appreciated!

推荐答案

你必须实际分配数组;并且您会想要使用指针类型,float array[] 不是您所想的那样.正如 juanchopanza 提醒我们的那样,您还需要禁用复制构造函数和赋值运算符,或者实现进行适当深度复制的构造函数和赋值运算符.

You have to actually allocate the array; and you'll want to use a pointer type, float array[] is not what you think there. As juanchopanza reminds us, you'll also want to either disable the copy constructor and assignment operator, or implement ones that do a proper deep copy.

//Inside Header
class runningAverage{
    private:
        byte n;
        float *array; // <= correct type
    public:
        runningAverage(byte);
        ~runningAverage(); // <= you'll need a destructor to cleanup
    private:
        runningAverage(const runningAverage &);
        runningAverage & operator = (const runningAverage &);
};

//Inside .cpp
runningAverage::runningAverage(byte a){
    array = new float[n]; // <= allocate array
    n = a;
    for (byte i = 0; i<n; i++) {
        array[i] = 0;
    }
}

// clean up
runningAverage::~runningAverage(){
    delete[] array;
}

但是,如果您有一些动态的、自动的容器可供您使用(例如 std::vector),您可能想要使用它 - 那么您不必处理复制/分配/析构函数/内存管理.

However, if you have some dynamic, automatic container at your disposal (e.g. std::vector) you might want to use that instead - then you don't have to deal with copy / assignment / destructor / memory management.

这篇关于在类中初始化可变大小的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆