C/C++变量做结构体数组长度
先看一下C/C++定义可变数组的方法:[C/C++变量做数组长度]
(https://blog..net/lyq_12/article/details/81773601) 用MFC做抓猴子的小游戏,用同样的方法在头文件中定义结构体数组报错。
protected: // create from serialization only CCatchMonkeyView(); DECLARE_DYNCREATE(CCatchMonkeyView) // Attributes public: CCatchMonkeyDoc* GetDocument(); int sum; //猴子总数 int remain; //剩余猴子数 int height; int width; struct MONKEY{ float x; float y; bool isCatched; }; MONKEY* monkey; monkey = new MONKEY[sum]; //通过指针动态申请空间
报错信息
error C2327: CCatchMonkeyView::sum : member from enclosing class is not a type name, static, or enumerator error C2258: illegal pure syntax, must be = 0
问题出在不能在头文件中给数组分配空间,申请空间的操作应该在构造函数初始化时候完成。
正确姿势 在头文件中声明,构造函数中分配空间。
public: CCatchMonkeyDoc* GetDocument(); int sum; //猴子总数 int remain; //剩余猴子数 int height; int width; struct MONKEY{ float x; float y; bool isCatched; }; MONKEY* monkey;
CCatchMonkeyView::CCatchMonkeyView() { // TODO: add construction code here width=height=0; sum=10; monkey = new MONKEY[sum]; //通过指针动态申请空间 remain=0; for(int i=0;i<sum;i++){ monkey[i].x=rand()%800+1; monkey[i].y=rand()%450+1; monkey[i].isCatched=false; } srand((unsigned)time(NULL)); }