c++ - 如何在 C++ 中为固定大小的数组类创建模板定义?

标签 c++ arrays templates

我需要创建一个模板,因为我不知道它是什么数组。它的大小必须是构造函数中传递的大小。所以这就是我得到的,我遇到了各种各样的错误。我是 C++ 的初学者,所以非常感谢您的帮助:)

template <typename T, int N>
class Array
{
  public:
    T& operator[](int index)
    {
      return data[index];
    }
  private:
    int size;
    T *data[N];
};

我想你明白我想做什么。如您所见,我还需要重载下标运算符。不确定我是否需要引用或指针或什么。我确实有一个构造函数,但它不能正常工作。

最佳答案

这是一个更正后的版本,其中还有一个示例 main:

#include <iostream>
using namespace std;

template <typename T, int N>
class Array
{
  public:
    T& operator[](int index)
    {
      // add check for array index out of bounds i.e. access within 0 to N-1
      return data[index];
    }
    Array() {
        data = new T[size = N];
    }
    ~Array() {
        if (data)
            delete [] data;
    }
  private:
    int size;
    T *data;
};

int main(void) {
    Array<int, 4> a;
    a[0] = 5;
    cout << a[0] << endl;
    return 0;
}

关于c++ - 如何在 C++ 中为固定大小的数组类创建模板定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24752027/

相关文章:

c++ - 在 BST 中找到第二个键

ruby-on-rails - Rails 3 模板 : strange beahaviour of inject_into_file

C++ 模板作为模板的参数

javascript - 从php数组的输​​入文件列表中删除特定文件

ios - 执行后显示数组

在游戏中将输入转换为大写

c++ - 编写接受 cv::Mat 或 cv::UMat 类型输入的模板函数

c++ - 我可以在 C++ 中做/模仿这样的事情(部分覆盖)吗?

c++ - 将代码内的所有具体注释收集到表格中

c++ - 自动和友元函数的返回类型匹配