c++ - 有没有一种方法可以使用非常量变量初始化数组? (C++)

标签 c++ arrays

我正在尝试创建一个这样的类:

class CLASS
{
public:
    //stuff
private:
    int x, y;
    char array[x][y];
};

当然,直到我将int x, y;更改为
const static int x = 10, y = 10;

这是不切实际的,因为我正在尝试从文件中读取x和y的值。那么,有什么方法可以使用非常量值初始化数组,或者声明数组并在不同的语句中声明其大小?而且我知道这可能需要创建一个数组类,但是我不确定从哪里开始,并且当数组本身不是动态的时,我不想创建一个二维动态列表,只是大小是在编译时未知。

最佳答案

编译器在编译时需要具有该类的确切大小,您将必须使用new运算符动态分配内存。

切换char数组[x] [y];到char **数组;并在构造函数中初始化数组,不要忘记在析构函数中删除数组。

class MyClass
{
public:
    MyClass() {
        x = 10; //read from file
        y = 10; //read from file
        allocate(x, y);
    }

    MyClass( const MyClass& otherClass ) {
        x = otherClass.x;
        y = otherClass.y;
        allocate(x, y);

        // This can be replace by a memcopy
        for( int i=0 ; i<x ; ++i )
            for( int j=0 ; j<x ; ++j )
                array[i][j] = otherClass.array[i][j];
    }

    ~MyClass(){
        deleteMe();
    }

    void allocate( int x, int y){
        array = new char*[x];
        for( int i = 0; i < y; i++ )
            array[i] = new char[y];
    }

    void deleteMe(){
        for (int i = 0; i < y; i++)
           delete[] array[i];
        delete[] array;
    }

    MyClass& operator= (const MyClass& otherClass)
    {
        if( this != &otherClass )
        {
            deleteMe();
            x = otherClass.x;
            y = otherClass.y;
            allocate(x, y);
            for( int i=0 ; i<x ; ++i )
                for( int j=0 ; j<y ; ++j )
                    array[i][j] = otherClass.array[i][j];            
        }
        return *this;
    }
private:
    int x, y;
    char** array;
};

*编辑:
我有复制构造函数
和赋值运算符

关于c++ - 有没有一种方法可以使用非常量变量初始化数组? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23753028/

相关文章:

java - 如何正确更新我的字符串数组?

c++ - 使用 boost::bind 结果作为参数

c++ - UDP 广播未收到

c - 从左到右、从上到下翻转图像

c - 数组被视为常量指针,所以我们不能更改指针值但数组的单个元素可以更改,为什么?

python - 使用 numpy 在公差范围内查找接近 float 的数组中的第一个元素的索引

arrays - 如何将长格式(可能稀疏)的 DataFrame 转换为多维 Array 或 NamedArray

c++ - 如果我有角度和轴,如何在 PCL 中进行旋转平移?

c++ - 是否可以在头文件中重载运算符(在声明类时)?

java - 需要锁定静态数组变量吗?