关于初始化数组
类定义如下:
class CCorpStructInterpolate
{
public:
__int64 getTag() const {return m_nTotalTag;}
private:
__int64m_nTotalTag;
};
通过如下语句获得:
__int64 size=g_pTrigram-> getTag();
double pdProb[size];
以上语句报错:error C2057: expected constant expression;
error C2466: cannot allocate an array of constant size 0
谢谢
[解决办法]
double pdProb[size];
定义数组时,编译器要知道数组的大小,很明显,楼主的程序做不到这点。
[解决办法]
1.调用getTag()的实例应该为const
2.数组定义时要其大小要确定,不然编译器会报错/
[解决办法]
error C2466: cannot allocate an array of constant size 0====> 说明数组定义时大小没确定
不过我记得有中关于零元素的数组应用
[解决办法]
__int64 size=g_pTrigram-> getTag();
楼主这句交待不够,g_pTrigram的定义在哪里?
我觉得可以改成这样:
class CCorpStructInterpolate
{
public:
CCorpStructInterpolate(int size):m_nTotalTag(size){} //缺省构造函数
__int64 getTag() const {return m_nTotalTag;}
private:
__int64m_nTotalTag;
};
int main()
{
CCorpStructInterpolate *p=new CCorpStructInterpolate(5); //为新对象分配内存,并
__int64 size=g_pTrigram-> getTag(); //用5来初始化
double *pdProb=new double[size]; //用动态分配内存来建立此数组
return 0;
}
[解决办法]
编译,链接通过了,但是运行是貌似是内存泄露了
最后要delete []pdProb;
[解决办法]
编译时要编译器要知道size的明确大小,最后当然要delete[] 数组名