我试图从一个函数返回一个常量的int std :: array,但是我遇到了错误而且我不知道如何修复它们 .
始终不应更改 refmatrix
中的这些值 . 's why I' m使用常量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
1 回答
该错误与返回
std::array
无关 . 它与分配给const
有关 .您需要使用调用初始化
resp
,而不是默认初始化然后分配 .See it live