在C++中组合两个类型为T的数组
Combining two arrays of type T in C++
我目前正试图重载+
运算符,以便组合两个类型为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;
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 可以将两个相同类型的连续数组视为一个数组吗?
- 如何允许模板参数中的类类型,仅当它有两个基类时
- 测试两个类型列表中的所有组合
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 堆栈分配的类类型.为什么两个 ID 实例的地址相同?
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 如何创建两个具有相同名称和不同返回类型并基于布尔参数运行的函数
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 比较两个整数在C++中与未知 int 类型的相等性
- 为什么C++不允许两个同名的函数/类模板,区别仅在于非类型模板参数(整型)的类型?
- [[no_unique_address]] 和两个相同类型的成员值
- C++stoi:这两个重载都无法转换所有参数类型
- 类型测试对象的动态数组的这两个声明之间的区别?
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- C++将两个不同类型的向量的属性连接到新的向量中
- 使用相同名称类型的两个不同库
- 重写虚函数协变返回类型(两个指针)
- 在c++中,如何在另一个嵌套类中使用嵌套类类型(两个嵌套类在同一个外部类下)