简单地说,我有一个模板类 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/