gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 12:34:22 25 4
gpt4 key购买 nike

所以我在文件 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/

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