c++ - 类 - 用户定义的具有动态大小的智能阵列

标签 c++ arrays class memory-management operator-overloading

我正在编写以下数组(类),当此数组的索引大于此数组的大小时,它会增加大小。 我知道 vector ,但它必须是数组。代码如下所示:

#include <iostream>

using namespace std;

class Array {

public:
Array():_array(new float[0]), _size(0){};
~Array() {delete[] _array;}
friend ostream &operator<<(ostream&,const Array&);
float& operator[] (int index) 
{
  if(index>=_size)
  {
    float* NewArray=new float[index+1];
    for(int i=0;i<_size;++i) NewArray[i]=_array[i];
    for(int i=_size;i<index+1;++i) NewArray[i]=0; 
    delete[] _array;
    _array=NewArray;
    _size=index+1;
  }
  return _array[index];
}

private:
  float *_array; // pointer to array
  int _size; // current size of array
};

ostream &operator << ( ostream &out,  const Array& obj) // overloading operator<< to easily print array
{
  cout << "Array:\n\n";
  for (int i=0;i<obj._size;++i) 
  {
    cout << obj._array[i];
    if(i+1!=obj._size) cout << ", "; 
  }
  cout << ".\n";
  return out;
}

int main()
{
  Array CustomArray;
  CustomArray[2] = CustomArray[1] = CustomArray[0] = 3.14; // **here is the problem**
  cout << CustomArray << endl;
}

一切正常,0 个警告,0 个 valgrind 错误,输出:

3.14, 3.14, 3.14.

我必须以这种方式编写此代码(在 main 中):

CustomArray[0] = CustomArray[1] = CustomArray[2] = 3.14;

现在是 3 个 valgrind 错误: 地址 (some_address) 是一个大小为 8 的 block 内的 4 个字节,

输出如下:0, 0, 3.14.

不幸的是,我必须编写这段代码才能以第二种方式工作 (CustomArray[0] = CustomArray[1] = CustomArray[2] = 3.14;) 你们能帮忙吗?提前致谢

最佳答案

您需要通过使用持有对 Array 的引用的代理类型来解决此问题对象和传递给您的索引 operator[] .此代理类型将隐式转换为 float并可从 float 分配,使访问(主要是1)变得透明。

在这种情况下,我们也违反了三的规则,并实现了复制赋值运算符,将一个数组元素的值赋给另一个数组元素,这样 foo[0] = foo[1]按预期工作。

我们需要进行以下更改:

  1. 重命名现有的 operator[]并将其设为私有(private);它只会被代理类型使用。
  2. 创建一个新的 operator[]返回代理类型的值。
  3. 写下代理类型。

更改 1,在 Array 内部的定义:

friend class ArrayElement; // So that ArrayElement can use access()
private:
float& access(int index) 
{
  if(index>=_size)
  {
    float* NewArray=new float[index+1];
    for(int i=0;i<_size;++i) NewArray[i]=_array[i];
    for(int i=_size;i<index+1;++i) NewArray[i]=0; 
    delete[] _array;
    _array=NewArray;
    _size=index+1;
  }
  return _array[index];
}

变化 2:

// Inside of Array
public:
    ArrayElement operator[](int index);

// Implementation outside of Array
ArrayElement Array::operator[](int index) {
    return ArrayElement(*this, index);
}

变化 3:

class ArrayElement
{
    friend class Array; // So that Array can use our private constructor

private:
    ArrayElement(Array & array, int index) : array(array), index(index) { }

public:
    // Allows "foo[1] = 2"
    ArrayElement const & operator=(float v) const {
        array.access(index) = v;
        return *this;
    }

    // Violation of the rule of three, but it makes sense in this case.
    // Allows "foo[1] = foo[2]"
    ArrayElement const & operator=(ArrayElement const & other) const {
        array.access(index) = other;
        return *this;
    }

    // Allows "float x = foo[1]"
    operator float() const {
        return array.access(index);
    }

private:
    Array & array;
    int index;
};

(最后的小改动,您需要在 ArrayElement 的定义之前转发声明 Array 。)

See this working example .


1 这种方法的一个注意事项是对数组访问使用类型推断(C++11 中的 auto):

auto x = an_array[1];

现在x是一个 ArrayElement而不是 floatan_array[1] 时,它的值会发生变化。变化。试图将不同的浮点值分配给 x将更改 an_array[1] 中的值同样,自x只是该值的代理。

将此与 std::vector 的一般行为进行对比其中 auto x = a_vector[0]将导致 x是 vector 的元素类型,因此将保存存储在 vector 中的值的独立拷贝。

但是请注意,std::vector<bool>特化完全遵循我在此处给出的方法(返回代理对象),因此 it does have the same auto caveat !您可以将其视为对这种方法的祝福。

关于c++ - 类 - 用户定义的具有动态大小的智能阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388573/

相关文章:

c++ - 如何移动 3D 框以保持在旋转平面上?

c# - 为什么我不能在通用 IEnumerable 对象上调用 ToArray?

html - 如何用点替换逗号

c++ - 程序员何时使用空基优化 (EBO)

c++ - 类内的 GLFW 回调

c++ - () 和 = 在创建类实例时有什么区别?

c++ - 星期日历计算器

c++ - 在 Visual Studio 中制作非 GUI 服务器应用程序

javascript - 通过 javascript(包括 JSON 对象)访问在 Android 上使用 Java 创建的 JSON 数组

c++ - 为什么我不能只使用前向声明 C++ 来声明类的静态成员?