我有一个程序,其中对象数组的大小是在运行时确定的,因此它是动态分配的(二维数组,从文件中读取)。我还有一个将这些对象作为参数的函数。问题是如果函数参数是传递给函数的二维数组,则应确定第二维。但是,就我而言,事实并非如此。我的程序无法编译,因为原型(prototype)没有提到第 2 个维度。
这是我尝试过的:
//global variables
int residentCount=0;
int hospitalCount=0;
Resident** residents;
Hospital** hospitals;
bool readFromFiles(const string, const string, const int); //sizes are determined in here
void print(Hospital*[hospitalCount], Resident*[residentCount]); //declaration issue
我该如何解决这个问题?
最佳答案
您正在使用 C++ 编程,因此您应该:
- 尽可能避免自行动态分配和处理内存管理
- 利用具有自动存储期限的对象,遵循 RAII idiom
- 避免使用 C 风格的数组,实际上避免编写一般情况下只能像 C++ 一样编译的 C 代码
- 使用 C++ 提供的强大功能,尤其是那些捆绑在 STL 中的功能
- 避免在局部变量足够时使用全局变量
它可能是这样的:
typedef std::vector<Resident> Residents;
typedef std::vector<Hospital> Hospitals;
// passing by const reference:
void print(const std::vector<Hospitals>&, const std::vector<Residents>&);
int main()
{
std::vector<Hospitals> hospitals;
std::vector<Residents> residents;
...
} // <-- lifetime of automatics declared within main ends here
请注意 hospitals
和 residents
将是具有自动存储持续时间的对象,可以以与 C 风格的二维数组类似的方式使用。当执行超出main
的范围时,这些 vector 被破坏并且内存,它们的元素(包括它们的元素的元素)之前所在的位置被自动清理。
另请注意,我建议您通过 const 引用传递,即 const std::vector<Hospitals>&
,这会阻止创建传递对象的拷贝和 const
关键字明确地告诉调用者:“尽管您通过引用传递此对象,但我不会更改它。”
关于c++ - 如何解决将未知大小的二维数组传递给函数的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15574620/