c++ - Overloading assignment operator in order to return std::vector -
the function below converts contents stored in class cvector, std::vector , returns this.
template <class t> std::vector<t> cvector<t>::converttostdvector() { std::vector<t> vec; vec.resize(m_nsize); (unsigned = 0; < m_nsize; ++i) { vec[i] = m_pdata[i]; } return vec; } the above works perfect, instead of using function this, overload assignment operator , same thing.
i've tried following:
template <class t> class cvector { public: cvector(unsigned nsize, allocenum ealloctype=malloc); cvector(t *pdata, unsigned nsize, bool bcopy=false); // convert 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); (unsigned = 0; < m_nsize; ++i) { vec[i] = m_pdata[i]; } return vec; } this compiles fine, when try call in code, e.g.
std::vector<float> vec = cvectorinstance; than following error during compilation:
error: conversion 'cvector' non-scalar type 'std::vector >' requested"
i'm not sure going wrong here, hope can / explain.
the assignment operator looks this:
class c { public: c& operator=(const c& other) {...} }; it used assign instance of class c not of class. can overload it, takes objects of other classes , assigns them class not other way around. so
cvector& operator=(const std::vector<...>& other) { ... } would take values inside other , assign them cvector. if want other thing use converttostdvector function.
Comments
Post a Comment