简体   繁体   English

重载赋值运算符以返回std :: vector

[英]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. 下面的函数将存储在类cVector的内容转换为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;
}

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" 错误:从'cVector'转换为非标量类型'std :: vector>''

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. 您定义的赋值运算符实际上是用于将cVector转移到另一个cVector,而不是转换为std::vector ,这是您想要的。

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. 它用于将某些内容分配给C类的实例而不是其他类的内容。 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 . 将值放在other值中并将它们分配给您的cVector If you want to do the other thing just use your convertToStdVector function. 如果你想做另一件事,只需使用你的convertToStdVector函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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