【发布时间】:2014-05-01 11:22:34
【问题描述】:
当我构造一个 TestCase 时,我会初始化我的类 TestCase 的一个 const int 成员 (numGrids)。它需要是 const (我认为),因为它定义了该类的另一个数组成员的元素,我也想在创建 TestCase 时对其进行初始化。代码如下:
///////////////////////////////////////// ////////////////////////////// //TestCase.h 类测试用例 { 受保护: 常量 int numGrids; 网格网格[numGrids]; 上市: 测试用例(常量 int); }; ///////////////////////////////////////// ////////////////////////////// //TestCases.cpp TestCase::TestCase(const int numGridsSpec) { numGrids = numGridsSpec; 网格网格[numGrids]; }我似乎无法初始化我班级的 const 成员。我需要该成员保持不变,因为它定义了网格的数组大小。我收到以下错误:
[ 12%] 构建 CXX 对象源/CMakeFiles/GridRefinementStudy.dir/TestCase.cpp.o 在 /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.cpp:16:0 中包含的文件中: /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.h:5:12:错误:非静态数据成员“TestCase::numGrids”的使用无效 /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.h:6:14:错误:来自这个位置 /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.h:6:22:错误:数组绑定在“]”标记之前不是整数常量 /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.cpp:在构造函数“TestCase::TestCase(int)”中: /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.cpp:25:1: 错误:未初始化的成员 ‘TestCase::numGrids’ 与 ‘const’ 类型 ‘const int’ [-fpermissive] /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.cpp:28:13:错误:分配只读成员‘TestCase::numGrids’ /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.cpp:29:21:错误:没有匹配函数调用‘Grid::Grid()’ /home/omar/Documents/Programming/C++/FCFD/Current/sources/TestCase.cpp:29:21:注意:候选人是: /home/omar/Documents/Programming/C++/FCFD/Current/sources/Grid.h:13:2: 注意:Grid::Grid(int, int, double, double) /home/omar/Documents/Programming/C++/FCFD/Current/sources/Grid.h:13:2:注意:候选人需要 4 个参数,提供 0 个 /home/omar/Documents/Programming/C++/FCFD/Current/sources/Grid.h:1:7:注意:Grid::Grid(const Grid&) /home/omar/Documents/Programming/C++/FCFD/Current/sources/Grid.h:1:7:注意:候选人需要 1 个参数,提供 0 make[2]: *** [sources/CMakeFiles/GridRefinementStudy.dir/TestCase.cpp.o] 错误 1 make[1]: *** [sources/CMakeFiles/GridRefinementStudy.dir/all] 错误 2 make: *** [全部] 错误 2【问题讨论】:
-
数组大小必须是编译时常量表达式。您要么想要
std::vector或std::array。 -
你需要初始化列表来初始化常量。我建议将数组更改为 std::vector。
-
请正确编辑您的代码!我开始了,剩下的留给你...
-
@KerrekSB 他还需要
std::array的编译时间常数。 -
一个(可能是丑陋的)解决方案是将
size_t numGrids作为模板参数传递,因为 OP 认为数组的大小在编译时是已知的。
标签: c++ constructor initialization constants