在C++中组合两个类型为T的数组

Combining two arrays of type T in C++

本文关键字:类型 两个 数组 C++ 组合      更新时间:2023-10-16

我目前正试图重载+运算符,以便组合两个类型为T的数组,但在过去一个小时左右的时间里,我遇到了麻烦。我想在不使用stl的情况下完成这项工作,因为我是C++的初学者,在使用标准类之前,我想很好地掌握实现类的方法。

上下文是,我目前正在使用模板化的动态分配数组设计自己的vector类。

因此,在这一点上,我感兴趣的是重载+运算符,以便在主函数内执行c = a + b时,其中a , b , cVector<T>对象,c将成为这两者的组合(串联)。

我真的无法理解这一点,因为定义运算符行为的函数最多只能处理一个参数。

有人能提出什么想法吗?

试试这个:

template<typename T>
class Vector
{
private:
    T *m_array;
    int m_count;
public:
    Vector()
        : m_array(NULL), m_count(0)
    {
    }
    Vector(const Vector &src)
        : m_array(NULL), m_count(0)
    {
        T* new_array = new T[src.m_count];
        for (int x = 0; x < src.m_count; ++x)
            new_array[x] = src.m_array[x];
        m_array = new_array;
        m_count = src.m_count;
    }
    ~Vector()
    {
        delete[] m_array;
    }
    // mutilator and accessor functions ...
    Vector& operator=(const Vector &rhs)
    {
        if (this != &rhs)
        {
            T* new_array = new T[rhs.m_count];
            for (int x = 0; x < rhs.m_count; ++x)
                new_array[x] = rhs.m_array[x];
            T* old_array = m_array;
            m_array = new_array;
            m_count = rhs.m_count;
            delete[] old_array;
        }
        return *this;
    }
    Vector& operator+=(const Vector &rhs)
    {
        int new_count = m_count + rhs.m_count;
        T* new_array = new T[new_count];
        for (int x = 0; x < m_count; ++x)
            new_array[x] = m_array[x];
        for (int x = 0; x < rhs.m_count; ++x)
            new_array[m_count+x] = rhs.m_array[x];
        T* old_array = m_array;
        m_array = new_array;
        m_count = new_count;
        delete[] old_array;
        return *this;
    }
};
template<typename T>
Vector operator+(const Vector<T> &lhs, const Vector<T> &rhs)
{
    // if you want to optimize this further, make this operator
    // a 'friend' of the Vector class so it can access the
    // m_array and m_count fields directly, then it can perform
    // one allocation+copy instead of two...
    Vector<T> v(lhs);
    v += rhs;
    return v;
}

Vector a, b, c;
// add items to a and b ...
c = a + b;
相关文章: