1

假设我有一堂课...

class Foo
{
public:
  Foo(int size);

private:
  const int size;
  int data[];
};

假设在实例化时立即设置 size 字段,如何data根据该 size 输入设置长度?

我通常会在std::vector这里使用 a ,但我正在为 Arduino 编写一个库,所以它不会飞,如果可以的话,我会尽量避免外部依赖。

4

1 回答 1

6

您在这里不走运,因为 C++ 必须在编译时知道数组的大小(换句话说,size必须是常量表达式)。您的选择是使用动态分配

int* data;  

new int[size];然后在构造函数初始化列表中分配 with ,或者更好的是使用std::unique_ptr<>(C++11 或更高版本),它是原始指针周围的轻量包装器,并在范围退出时删除其分配的内存,因此您不必手动delete[]

class Foo
{
private:
    std::unique_ptr<int[]> data; // no need to manually delete
public:
    Foo(int size): data{new int[size]} {}
};

第三种选择是制作Foo一个非类型模板类(假设您在编译时知道大小,这似乎正在发生,至少从您的问题来看)

template<std::size_t size>
class Foo
{
    int data[size];
public:
    Foo() 
    {
        // constructor here
    }
};
于 2016-01-26T01:49:15.063 回答