我有以下简单的示例代码:
1。
//param.h
extern int n;
2。
//param.cpp
int n =10;
3。
# include <iostream>
# include "param.h"
using namespace std;
int main()
{
double Arr[n];
return 0;
}
由于无法定义n,因此无法编译。
为什么,在保持相同结构的情况下解决此问题的最佳方法是什么?
n
是非常量的:您不能使用n
大小声明静态数组。正如@NickyC在评论中指出的,简单的解决方案是将数组替换为std :: vector:
#include <vector>
std::vector<double> Arr(n/*, default_value*/);
如果要继续使用数组,则必须声明n
为const:
// param.h
extern const int n;
// param.cpp
const int n = 10;
或声明一个动态数组:
double* Arr = new double[n];
...
delete[] Arr;
return 0;
或使用托管指针更好:
#include <memory>
std::unique_ptr<double[]> Arr = std::make_unique<double[]>(n);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句