gpt4 book ai didi

c++ - 高度不是常数表达式

转载 作者:行者123 更新时间:2023-11-28 00:44:34 24 4
gpt4 key购买 nike

如何在构造函数中为二维数组分配动态内存,同时让我的 std::unique_ptr 处理它的释放?或者有更好的方法吗?

我的错误是“高度不是常量表达式”。

#include <iostream>
#include <vector>
#include <memory>

template<typename T>
class Matrix
{
private:
int Width, Height;
std::unique_ptr<T*> Elements;

public:
Matrix(int Width, int Height);

T* operator[](int Index);
const T* operator[](int Index) const;
};

template<typename T>
Matrix<T>::Matrix(int Width, int Height) : Width(Width), Height(Height), Elements(new T[Width][Height]) {}

template<typename T>
T* Matrix<T>::operator[](int Index) {return Elements[Index];}


int main()
{
Matrix<int> M(4, 4);
std::cout << M[2][2];
}

最佳答案

您需要使用动态数组习惯用法。分配一个一维 vector 并转换坐标。类似于:, Elements( new T[Width*Height] ) .然后你需要在你的 operator[] 中做数组转换,像这样:return Elements.get()+Index*Height;

顺便说一下,你的 unique_ptr应该是 unique_ptr<T[]>而不是 T* .如果您使用 new[] 进行分配, 你需要一个 unique_ptr<...[]>确保使用 delete[] 回收它.

关于c++ - 高度不是常数表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16974490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com