如何从一个方法返回一个静态const int std :: array?
我试图从一个函数返回一个常量int std ::数组,但我得到的错误,我不知道如何解决它们。
refmatrix
这些值不应该改变。 这就是我使用常量int的原因。
reference.h
#include <array>
#include <iostream>
using namespace std;
class Reference {
public:
static const size_t NCOLS = 3;
static const size_t NBITS = 4;
static const size_t NROWS = 4;
private:
static array<array<array<const int, NBITS>, NCOLS>, NROWS> refmatrix;
public:
Reference();
~Reference();
array<const int, NBITS> smaller(int *arry);
};
reference.cpp
#include "reference.h"
array<array<array<const int, Reference::NBITS>, Reference::NCOLS>, Reference::NROWS> Reference::refmatrix = {{{{{0, 1, 2, 6}, {6, 4, 1, 7}, {6, 7, 8, 3}}},
{{{7, 0, 5, 2}, {1, 6, 9, 3}, {1, 4, 8, 0}}},
{{{9, 3, 4, 6}, {0, 7, 2, 8}, {5, 3, 9, 4}}},
{{{8, 9, 1, 4}, {7, 2, 6, 0}, {4, 0, 3, 7}}}}};
Reference::Reference() {}
Reference::~Reference() {}
array<const int, Reference::NBITS> Reference::smaller(int *arry) {
int j;
for(int i=0; i < NROWS; i++){
for(j=0; j < NCOLS; j++){
if(refmatrix[i][0][j] != arry[j]){
j = (NCOLS + 1);
}
}
if(j == NCOLS){
return refmatrix[i][1];
}
}
}
main.cpp中
#include "reference.h"
int main() {
Reference r;
int arr[3] = {0, 1, 2};
array<const int, Reference::NBITS> resp;
resp = r.smaller( arr );
// After get these values I will write it in a file.
return 0;
}
main.cpp: In function ‘int main()’: main.cpp:6:37: error: use of deleted function ‘std::array<const int, 4>::array()’ array<const int, Reference::NBITS> resp; ^~~~ In file included from reference.h:1:0, from main.cpp:1: /usr/include/c++/7.3.0/array:94:12: note: ‘std::array<const int, 4>::array()’ is implicitly deleted because the default definition would be ill-formed: struct array ^~~~~ /usr/include/c++/7.3.0/array:94:12: error: uninitialized const member in ‘struct std::array<const int, 4>’ /usr/include/c++/7.3.0/array:110:56: note: ‘const int std::array<const int, 4>::_M_elems [4]’ should be initialized typename _AT_Type::_Type _M_elems; ^~~~~~~~ main.cpp:9:33: error: use of deleted function ‘std::array<const int, 4>& std::array<const int, 4>::operator=(std::array<const int, 4>&&)’ resp = r.smaller( arr ); ^ In file included from reference.h:1:0, from main.cpp:1: /usr/include/c++/7.3.0/array:94:12: note: ‘std::array<const int, 4>& std::array<const int, 4>::operator=(std::array<const int, 4>&&)’ is implicitly deleted because the default definition would be ill-formed: struct array ^~~~~ /usr/include/c++/7.3.0/array:94:12: error: non-static const member ‘const int std::array<const int, 4>::_M_elems [4]’, can’t use default assignment operator
该错误与返回std::array
无关。 这与分配给const
。
您需要初始化resp
与呼叫,而不是默认初始化,然后分配。
int main() {
Reference r;
int arr[3] = {0, 1, 2};
array<const int, Reference::NBITS> resp = r.smaller( arr );
// After get these values I will write it in a file.
return 0;
}
现场看到它
链接地址: http://www.djcxy.com/p/67331.html上一篇: How to return a static const int std::array from a method?