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

标签 c++ arrays operator-overloading

我目前正在尝试使 + 过载运算符以组合两个 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;

关于c++ - 在 C++ 中合并两个类型为 T 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29312736/

相关文章:

c++ - 将一维数组的索引转换为二维数组

java - 从另一个数组创建一个随机字符串数组。

c++ - 如何在 C++ 中同时为整数、 float 和 double 据类型重载运算符

c++ - 'operator<<(std::ostream&, int&)' 不明确

c++ - 错误 : argument of type "float(*)[1] " is incompatible with parameter of type "float** "

c++ - 使用指针/引用影响本地成员的多态调用

c++ - Const 对 Copy Constructor 重要吗?

c++ - 确定性地生成加密安全 key 和 IVEC

ruby - 如何以更简洁的方式重写这个 Ruby 循环

c++ - 是否有打印可选值的约定?