我在寫一個封裝了二維數組的類。這是複製構造函數。 (WIDTH
和HEIGHT
是編譯時間常數,這就是爲什麼我認爲這適合使用數組。)爲什麼我不能在我的拷貝構造函數中使用std :: copy?
MyClass::MyClass(const MyClass &other)
{
std::copy(
&array[0][0], &array[0][0] + WIDTH*HEIGHT,
&other.array[0][0]);
}
我使用,根據this question是正確的方法,以及工作之前,我改變了原型是const &
而不是簡單的傳值。不過,我現在收到此編譯器錯誤:
In file included from /usr/include/c++/4.8/bits/char_traits.h:39:0,
from /usr/include/c++/4.8/string:40,
from MyClass.hpp:4,
from MyClass.cpp:1:
/usr/include/c++/4.8/bits/stl_algobase.h: In instantiation of ‘_OI std::__copy_move_a(_II, _II, _OI) [with bool _IsMove = false; _II = ArrayDataType*; _OI = const ArrayDataType*]’:
/usr/include/c++/4.8/bits/stl_algobase.h:428:38: required from ‘_OI std::__copy_move_a2(_II, _II, _OI) [with bool _IsMove = false; _II = ArrayDataType*; _OI = const ArrayDataType*]’
/usr/include/c++/4.8/bits/stl_algobase.h:460:17: required from ‘_OI std::copy(_II, _II, _OI) [with _II = ArrayDataType*; _OI = const ArrayDataType*]’
MyClass.cpp:17:28: required from here
/usr/include/c++/4.8/bits/stl_algobase.h:390:70: error: no matching function for call to ‘std::__copy_move<false, true, std::random_access_iterator_tag>::__copy_m(ArrayDataType*&, ArrayDataType*&, const ArrayDataType*&)’
_Category>::__copy_m(__first, __last, __result);
^
/usr/include/c++/4.8/bits/stl_algobase.h:390:70: note: candidate is:
/usr/include/c++/4.8/bits/stl_algobase.h:368:9: note: template<class _Tp> static _Tp* std::__copy_move<_IsMove, true, std::random_access_iterator_tag>::__copy_m(const _Tp*, const _Tp*, _Tp*) [with _Tp = _Tp; bool _IsMove = false]
__copy_m(const _Tp* __first, const _Tp* __last, _Tp* __result)
^
/usr/include/c++/4.8/bits/stl_algobase.h:368:9: note: template argument deduction/substitution failed:
/usr/include/c++/4.8/bits/stl_algobase.h:390:70: note: deduced conflicting types for parameter ‘_Tp’ (‘ArrayDataType’ and ‘const ArrayDataType’)
_Category>::__copy_m(__first, __last, __result);
我認爲C++標準不會使std::copy
不可用在通過這種方式不斷引用一個拷貝構造函數,所以我究竟錯在這裏做什麼?
'std :: copy'在多維數組中遇到問題,但是您還沒有向我們提供它們的定義。如果你的拷貝構造函數只執行每個元素的拷貝,那麼你不需要提供它。編譯器自動生成一個。 – 2015-03-25 04:59:11
爲什麼不使用'std :: array'? – 2015-03-25 04:59:20
你寫它的方式是不是試圖將'array'複製到'other.array'而不是其他方式? – user2357112 2015-03-25 05:00:22