下面的函數將存儲在類cVector
中的內容轉換爲std::vector
,並返回它。重載賦值運算符以返回std :: vector
template <class T> std::vector<T> cVector<T>::convertToStdVector()
{
std::vector<T> vec;
vec.resize(m_nSize);
for (unsigned i = 0; i < m_nSize; ++i) {
vec[i] = m_pData[i];
}
return vec;
}
上述作品完美,現在不是使用這樣的功能,我想重載賦值操作符,基本上做同樣的事情。
我已經試過如下:
template <class T> class cVector
{
public:
cVector(unsigned nSize, AllocEnum eAllocType=MALLOC);
cVector(T *pData, unsigned nSize, bool bCopy=false);
// convert to std vector
std::vector<T> operator=(const cVector<T> &cvec);
//..
//....
}
template <class T> std::vector<T> cVector<T>::operator=(const cVector<T> &cvec)
{
std::vector<T> vec;
vec.resize(m_nSize);
for (unsigned i = 0; i < m_nSize; ++i) {
vec[i] = m_pData[i];
}
return vec;
}
編譯沒有問題,但是當我嘗試調用它在我的代碼,例如
std::vector<float> vec = cVectorInstance;
比我得到的編譯過程中出現以下錯誤:
error: conversion from 'cVector' to non-scalar type 'std::vector >' requested"
我不知道是怎麼回事錯在這裏,我希望有人能幫助/解釋。
你不應該用返回值重載。這純粹是錯誤的。 –
分配運營商應該返回對「* this」的引用。 – HatsuPointerKun
爲什麼你想首先編寫自己的矢量類?無論你想達到什麼目標,都可能已經可以實現(並且以更好的方式實現),使用'std :: vector'。 –