我目前正在尝试使 +
过载运算符以组合两个 T
类型的数组,但过去一个小时左右我一直在碰壁。
我想在不使用 stl
的情况下执行此操作因为我是 C++
的初学者我想在使用标准类之前很好地掌握实现类。
上下文是我目前正在设计一个 vector
我自己的类,使用模板化的动态分配数组。
因此,此时我感兴趣的是重载 +
运算符,以便在执行 c = a + b
时在主函数中,a , b , c
是 Vector<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/