我有一个采用数组及其大小的类。在类中,我有一个索引运算符“ []”,该运算符已重载以将其内容传递给类成员函数并返回该函数。它还会检查我是否正在访问超出数组大小的内容。
this_type operator[] (int index)
{
assert (index > 0 && index<=len);
at(index);
return c_arr()[index];
}
我为此制作了一个复制构造函数
//constructor
my_array(this_type const arr[], int size)
{
len = size;
assert(arr != NULL);
assert(size >= 0);
this->arr = new this_type[size];
for (int i = 0; i < size; i++)
(*this).arr[i] = arr[i];
}
//copy constructor
my_array( const my_array<this_type> & arr)
{
this->arr = new this_type[sizeof(arr)];
memcpy(this->arr, arr.arr, sizeof(this_type)*arr.len);
}
my_array(int size)
{
len = size;
assert(size >= 0);
this->arr = new this_type[size];
}
但是,当调用成员函数“ len”时,似乎没有传递数组大小值。有什么想法吗?
#include <iostream>
#include <cassert>
#include <assert.h>
using namespace std;
template <class this_type>
class my_array
{
private:
this_type *arr;
int len;
int sum()
{
int sum;
for (int i = 0; i < len; i++)
sum += arr[i];
}
public:
int size() const
{
return len;
}
this_type &at(int index)
{
assert( index >= 0 && index < len);
return arr[index];
}
my_array(this_type const arr[], int size)
{
len = size;
assert(arr != NULL);
assert(size >= 0);
this->arr = new this_type[size];
for (int i = 0; i < size; i++)
(*this).arr[i] = arr[i];
}
my_array( const my_array<this_type> & arr)
{
this->arr = new this_type[sizeof(arr)];
memcpy(this->arr, arr.arr, sizeof(this_type)*arr.len);
}
my_array(int size)
{
len = size;
assert(size >= 0);
this->arr = new this_type[size];
}
~my_array()
{
delete[] arr;
}
this_type* c_arr()
{
return arr;
}
this_type & operator[] (int index)
{
assert (index > 0 && index<=len);
at(index);
return c_arr()[index];
}
this_type operator[] (int index)
{
assert (index > 0 && index<=len);
at(index);
return c_arr()[index];
}
friend istream & operator>>(istream &lhs, my_array<this_type> &rhs);
friend ostream & operator<<(ostream &lhs, my_array<this_type> &rhs);
};
template <class this_type>
ostream & operator<<(ostream &lhs, my_array<this_type>&rhs)
{
for ( int i = 0; i < rhs.size(); i++)
lhs << rhs.arr[i] << endl;
return lhs;
}
template <class this_type>
istream & operator>>(istream &lhs, my_array<this_type> &rhs)
{
for ( int i = 0; i < rhs.size(); i++)
lhs >> rhs.arr[i];
return lhs;
}
int main()
{
char arra[5]={'c','o','d','e','s'};
my_array<char> arr(arra,5), arr1(5), arr2(arr);
for(int t=0;t< 9;t++)
{
//use the operator that is attached to the class instance
cout << arr2[t];
}
for(int t=0;t< 9;t++)
{
cout<<arr2.c_arr()[t];
}
return 0;
}
this->arr = new this_type[sizeof(arr)];
复制构造函数中的这一行是不正确的。arr
是您my_array
班上的一个对象。sizeof(arr)
是一个编译时间常数,并且完全独立于为数组分配的元素数量。这些元素甚至都没有包含在类中。它们在免费商店中,并且该类持有指向它们的指针。您想要的是:
this->arr = new this_type[arr.len];
您还希望将其分配给正在构造的对象的len成员。
this->len = arr.len;
我不得不说,除非您出于学习目的而创建此类,否则请使用std::vector
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句