【发布时间】:2014-02-15 23:54:30
【问题描述】:
在问这个问题之前,我查看了this similar question 并尝试使用它的代码来解决我的问题,但是它没有工作。
我正在尝试编写一个扩展给定静态对象数组的函数。这是目前的功能,基于上述链接问题的代码:
void MyClass::expand_array(MyClass *&old_array, int &old_array_size,
int new_slots)
{
MyClass *transfer_array = new MyClass[old_array_size + new_slots];
for (int i = 0; i < old_array_size; i++) {
transfer_array[i] = old_array[i];
}
delete[] old_array;
old_array = transfer_array;
transfer_array = NULL;
}
这甚至不能编译。这是编译器的输出:
program.cpp:110:54: error: no matching function for call to ‘MyClass::expand_array(MyClass [10], int&, int)’
program.cpp:110:54: note: candidate is:
program.cpp:41:6: note: static void MyClass::expand_array(MyClass*&, int&, int)
program.cpp:41:6: note: no known conversion for argument 1 from ‘MyClass [10]’ to ‘MyClass*&’
program.cpp:122:54: error: no matching function for call to ‘MyClass::expand_array(MyClass [10], int&, int)’
program.cpp:122:54: note: candidate is:
program.cpp:41:6: note: static void MyClass::expand_array(MyClass*&, int&, int)
program.cpp:41:6: note: no known conversion for argument 1 from ‘MyClass [10]’ to ‘MyClass*&’
program.cpp:143:11: warning: deleting array ‘MyClass tmp_cards [10]’ [enabled by default]
(输出的最后一行来自尝试删除数组的最后一次迭代。)
【问题讨论】:
-
该错误与您调用该函数的方式有关。第一个参数引用一个指针,但您提供的是一个数组。
-
不相关,但考虑返回新数组。这是(更好的)自我记录。 (如果是我的代码,我根本不会修改 old_array 指针。但是,每个人都有自己的。)
-
@0x499602D2 那么,将数组传递给函数的正确方法是什么?
-
@jpaugh 原始数组需要通过其中几个操作来保持相同的名称,我认为返回是不可能的。另外,我不知道你可以在 C++ 中返回一个数组。
-
你不能返回指向任何东西的指针吗?但我离题了..
C++不是我的强项;祝你好运。
标签: c++ arrays memory-management