【发布时间】:2015-11-21 19:45:42
【问题描述】:
我确定这是重复的,但我所看到的一切都解释了如何为数组动态分配内存。我有一个固定长度的数组,我只想把它放在一个包装结构中以便于参考。这是最基本的代码:
头文件
#ifndef BOARD_T_H
#define BOARD_T_H
#include <iostream>
struct board_t {
board_t();
/* I've tried explicitly assigning length b[16] and just declaring
* b[]. Neither seem to work.
------------------------v */
board_t(unsigned int b[16]);
board_t(board_t& other);
unsigned int values[16];
};
#endif
CPP 文件
#include "board_t.hpp"
board_t::board_t(){
for (int i = 0; i < 16; ++i) values[i] = 0;
}
board_t::board_t(unsigned int b[16]) {
for (int i = 0; i < 16; ++i) {
values[i] = b[i];
}
}
board_t::board_t(board_t& other) {
for (int i = 0; i < 16; ++i) this->values[i] = other.values[i];
}
测试文件
#include "board_t.hpp"
int main(){
unsigned int arr[16];
for (int i = 0; i < 16; ++i ) arr[i] = i;
board_t b = board_t(arr);
}
编译错误
$ g++ test.cpp include/board_t.cpp -o test.out
test.cpp: In function ‘int main()’:
test.cpp:6:25: error: no matching function for call to ‘board_t::board_t(unsigned int [16])’
board_t b = board_t(arr);
^
test.cpp:6:25: note: candidates are:
In file included from test.cpp:1:0:
include/board_t.hpp:6:2: note: board_t::board_t(board_t&)
board_t(board_t& other);
^
include/board_t.hpp:6:2: note: no known conversion for argument 1 from ‘unsigned int [16]’ to ‘board_t&’
include/board_t.hpp:5:2: note: board_t::board_t()
board_t();
^
include/board_t.hpp:5:2: note: candidate expects 0 arguments, 1 provided
我知道有一些方法(比如使用 std::array 或 boost 等),但这真的让我很烦恼——我只需要知道如何让它工作!
如果这非常明显,再次抱歉。我尽量不要用重复来污染 SE,但有时我就是忍不住 ;)
【问题讨论】:
-
您可能只需要测试文件中的
board_t b(arr);。 -
是的,这很愚蠢。对不起各位,浪费大家时间!
-
在 C++ 中,编译器比任何人都“聪明”得多,所以人类犯的所有错误都是“愚蠢的”:)
-
" 我有一个固定长度的数组,我只想把它放在一个包装结构中以便于引用。" 你的意思是,像
std::array? -
注意这与数组无关
标签: c++ arrays constructor