c++ - 如何正确制作带有 templetad 数组的类对象?

标签 c++ class templates

所以我在文件 Node.h 中写了一个类“Node”作为树数据容器。它包含一个二维数组,其大小在编译时给出,但我只能从不同的类中获取它,而不是硬类型。我试过了

class Node {
    private:
        int array[size][size];

只有我自己

error: ‘fFieldSize’ was not declared in this scope

因此,我做了这样的事情:

template<int T,int Z>
class Node {
    private:
        int array[T][Z];

现在,我将这个文件包含在我想要的“引擎”类中

  1. 使用 Node 实例

  2. 使用返回类型Node的“Engine”的成员函数

    1. node<size,size> firstnode;
    2. Node GetData();
    

引擎有一个.h 和一个.cxx 文件。 我不知道如何使用成员函数来做这件事。

我试过了

Node<size,size> GetData;

但是我得到了错误:

error: invalid use of non-static data member ‘MyNAMESPACE::Engine::size’

帮助将不胜感激。另外,这是我的第一个问题,我希望我所做的一切都符合标准。

最佳答案

size 必须是 constconstexpr,因为模板参数必须在编译时已知。

否则需要动态收集,比如:

class Node {
    public:
        Node(int T,int Z) : array(T,std::vector<int>(Z,0))
        {}

    private:
        vector<vector<int>> array;

关于c++ - 如何正确制作带有 templetad 数组的类对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57062229/

相关文章:

C++ 映射行为不正常

c++ - 在 Mac OS X 上调试和终止应用程序?

c++ - 代码在 Sun Studio 上编译但在 gcc 上出错

c++ - 如何重载 == 运算符而不使其成为友元函数?

python - __init__() 缺少 1 个必需的位置参数 : 'name'

c++ - 递归 AsString() 在 C++ 中打印 STL 容器

c++ - OpenGL 3.3/GLSL 和 C++ 错误 : "must write to gl_Position"

python - 保持类松散耦合并共享数据

templates - Scala/Lift - 试图理解 Lift 同时声称使用有效的 html 和倾向性提升 : tags and tag rewriting in render

C++ 通用 int 数组和 vector 迭代器