C变量数组作为类成员
发布时间:2020-12-16 10:43:27 所属栏目:百科 来源:网络整理
导读:我有一个小C程序定义如下: class Test{ public: int a; int b[a];}; 编译时会产生错误: testClass.C:7:5: error: invalid use of non-static data member ‘Test::a’testClass.C:8:7: error: from this locationtestClass.C:8:8: error: array bound is n
我有一个小C程序定义如下:
class Test { public: int a; int b[a]; }; 编译时会产生错误: testClass.C:7:5: error: invalid use of non-static data member ‘Test::a’ testClass.C:8:7: error: from this location testClass.C:8:8: error: array bound is not an integer constant before ‘]’ token 我如何了解错误消息的含义,以及如何解决? 解决方法
在编译时不能使用具有未定义大小的数组.有两种方法:定义一个as static const int a = 100;并忘记动态大小或使用std :: vector,这比手动内存管理更安全:
class Test { public: Test(int Num) : a(Num),b(Num) // Here Num items are allocated { } int a; std::vector<int> b; }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |