c++ - 将指针数组传递给模板类方法

标签 c++ arrays templates pointers

简单地说,我有一个模板类 Tree,它有一个 createTree(Data* arrayData[]) 方法。此方法接收指向 Data 类型数据的指针数组:

template<class Data>
void Tree<Data>::createTree(Data* arrayData[]) {
    m_indexCreation = 0;
    cout << sizeof(arrayData) / sizeof(int) << endl;
    m_root = createChildTree(arrayData);
}

在我的 main() 函数中,我创建了一个指向字符串对象的指针数组并填充它。然后我尝试将它传递给 createTree() 方法,但在该方法中数组的大小变为 1。换句话说,方法中的计数打印“1”。 这是我的 main() :

int main() {
    string* tab[20];

    for ( int i = 0 ; i < 20 ; i++ ) {
        if ( i % 3 != 0 ) {
            tab[i] = new string("James Johnson");
        } else {
            tab[i] = NULL;
        }
    }

    Tree<string> tree;
    tree.createTree(tab);

    tree.display(tree.getRoot());
}

我可以毫无问题地在 main() 中打印整个数组的值,但是在 createTree() 中,数组以某种方式减小到 1 的大小,具有单个 NULL 值。

我做错了什么?

最佳答案

检查 C 常见问题

http://c-faq.com/aryptr/aryparmsize.html

A: The compiler pretends that the array parameter was declared as a pointer (that is, in the example, as char *a; see question 6.4), and sizeof reports the size of the pointer. See also questions 1.24 and 7.28.

解决方法。将大小作为参数传递。

void Tree<Data>::createTree(Data* arrayData[], int sz)
{
    ...
}

Tree<string> tree;
tree.createTree(tab, sizeof(tab)/sizeof(tab[0]));

关于c++ - 将指针数组传递给模板类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15857600/

相关文章:

c++ - 柔软、透明的笔画纹理没有像我预期的那样混合

javascript - 如何按键对对象数组进行分组?

Javascript - 在循环中构建数组

c# - 在不同类的方法中打印数组?

c++ - 模仿 std::function 模板参数

c++ - 带有 cocos2d-x 3 beta 2 的 Xcode 5.1 中的链接器错误

c++ - 将两个数组复制到一个更大的数组中?

C++:读取数据怎么可能影响内存?

C++、模板或指向成员函数的指针

javascript - Pug 从模板中的另一个文件调用 js 函数