我寫了模板拷貝構造函數代碼,以獲得更好的理解這個概念,因爲我是新來的,但下面的代碼編譯失敗C++模板拷貝構造函數不可用或明確
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
class Grid
{
public:
explicit Grid(size_t inWidth = kDefaultWidth, size_t inHeight = kDefaultHeight);
virtual ~Grid();
template <typename E>
Grid(const Grid<T>& src);
static const size_t kDefaultWidth = 10;
static const size_t kDefaultHeight = 10;
std::vector<std::vector<T>> mCells;
size_t mWidth, mHeight;
};
template <typename T>
template <typename E>
Grid<T>::Grid(const Grid<T>& src)
{
cout << "Copy constructor working " << endl;
}
int main()
{
Grid<double> myDoubleGrid;
Grid<double> newDoubleGrid(myDoubleGrid);
return 0;
}
在編譯上面以下錯誤Visual Studio代碼出現: -
錯誤: -
Severity Code Description Project File Line Suppression State Error C2558 class 'Grid': no copy constructor available or copy constructor is declared 'explicit'
我試圖爲E來代替參數的模板,它顯示了更多的錯誤(奇怪的)
template <typename T>
template <typename E>
Grid<T>::Grid(const Grid<E>& src)
{
cout << "Copy constructor working " << endl;
}
錯誤:
Severity Code Description Project File Line Suppression State Error LNK2019 unresolved external symbol "public: __thiscall Grid::Grid(unsigned int,unsigned int)" ([email protected]@@[email protected]@Z) referenced in function _main
Error LNK1120 2 unresolved externals
Error LNK2019 unresolved external symbol "public: virtual __thiscall Grid::~Grid(void)" ([email protected]@@[email protected]) referenced in function "public: virtual void * __thiscall Grid::`scalar deleting destructor'(unsigned int)" ([email protected]@@[email protected])
是的,我只是在公衆後面:訪問說明符 –
'Grid :: Grid(const Grid &src)'...'T'和'T',E有什麼用? –
它可能會在稍後使用,我打算將其用於其他目的,儘管它是可以忽略的 –