简体   繁体   中英

Overloading assignment operator in order to return std::vector

The function below converts the contents which is stored in the class cVector , to a std::vector and returns this.

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;
}

The above works perfect, now instead of using a function like this, I would like to overload the assignment operator and basically do the same thing.

I've tried the following:

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;
}

This compiles fine, however when I try to call it in my code, eg

std::vector<float> vec = cVectorInstance;

Than I get the following error during compilation:

error: conversion from 'cVector' to non-scalar type 'std::vector >' requested"

I'm not sure what is going wrong here, I hope somebody can help / explain.

The assignment operator you defined is actually for asignment of a cVector to another cVector, not a conversion to std::vector , which is what you want.

What you are looking for is overloading the conversion operator :

operator std::vector< T >() const { ... }

The assignment operator usually looks somewhat like this:

class C 
{
public:
    C& operator=(const C& other) {...}
};

It is used to assign something to an instance of the class C not to something of another class. You can overload it, so that it takes objects of other classes and assigns them to your class but not the other way around. So

cVector& operator=(const std::vector<...>& other) { ... }

would take the values inside other and assign them to your cVector . If you want to do the other thing just use your convertToStdVector function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM