我正在尝试在我的班级中使用C ++数组:
#include <array>
#include <iostream>
using namespace std;
class Test {
private:
const size_t NCOL = 4;
array<int, NCOL> row;
public:
Test(){}
~Test(){}
};
int main() {
Test t;
return 0;
}
但我收到以下错误消息,我不知道原因:
test.cpp:9:14: error: invalid use of non-static data member ‘Test::NCOL’ array<int, NCOL> row; ^~~~ test.cpp:8:23: note: declared here const size_t NCOL = 4; ^ test.cpp:9:14: error: invalid use of non-static data member ‘Test::NCOL’ array<int, NCOL> row; ^~~~ test.cpp:8:23: note: declared here const size_t NCOL = 4; ^ test.cpp:9:14: error: invalid use of non-static data member ‘Test::NCOL’ array<int, NCOL> row; ^~~~ test.cpp:8:23: note: declared here const size_t NCOL = 4; ^ test.cpp:9:18: error: template argument 2 is invalid array<int, NCOL> row;
我该如何解决这个问题?
答案 0 :(得分:1)
答案就在错误消息中:
无效使用非静态数据成员'Test :: NCOL'
NCOL
不是static
,因此它是Test
的每个实例的数据成员,并在构造Test
时在运行时获取其值。您无法在模板参数中使用运行时数据值。
让NCOL
改为static
,然后编译器可以将它用作编译时常量,就像你想要的那样:
static const size_t NCOL = 4;