gpt4 book ai didi

c++ - 如何在 C++ 类中创建私有(private)动态数组?

转载 作者:行者123 更新时间:2023-12-01 23:13:21 25 4
gpt4 key购买 nike

您好,我在类中使用动态数组时遇到问题。我被指示“VectorDouble 类将有一个用于动态 double 组的私有(private)成员变量”。我只是为这个程序编写了头文件,但我还没有超越这一点。一旦达到容量,该类的大小就需要能够增加一倍。这是我的代码:

#include <iostream>
using namespace std;

// VectorDouble class header file
class VectorDouble
{
public:
// constructor for an empty vector of type double
VectorDouble();
// constructor that take an int argument for an integer size of and array
VectorDouble(int initial_size);
// copy constructor
VectorDouble(VectorDouble &object);
// destructor to return dynamic memory to the freestore
~VectorDouble();
// overloaded operator = for VectorDouble class
VectorDouble& operator =(const VectorDouble &source);
// overloaded operator == for VectorDouble class
friend bool& operator ==(const VectorDouble &this_vector,
VectorDouble &other_vector);
// adds a new element at the end of the array
void push_back();
// returns allocated size of VectorDouble dynamic array
int capacity();
// returns used size of the VectorDouble object
int size();
// allocates a specified block of memory for specified number of double
// type values
void reserve(int new_reserve);
// changes the size of the dynamic array
void resize(int new_size);
// returns the value at the specified index
double value_at(int index);
// changes the value at the specified index to double value d
void change_value_at(double d, int index);

private:

int count;
int max_count;
int index_pointer;
*index_pointer = new double[100];

};

我收到的错误都在这一行:*index_pointer = new double[100];

  • `new' 不能出现在常量表达式中

  • ISO C++ 禁止声明没有类型的“index_pointer”

  • ISO C++ 禁止初始化成员“index_pointer”

  • 使“index_pointer”静态

  • 非整数的静态数据成员的类内初始化无效输入“int*”

最佳答案

你的指针需要一个类型。将该行更改为

double* index_pointer;

并在构造函数中添加以下行

index_pointer = new double[100];

其他构造函数和赋值运算符依此类推。

但这也是一个命名冲突,因为你有另一个名为index_pointer的私有(private)int成员。我不确定该成员的用途,但如果您确实需要它,那么您必须将其或指针命名为其他名称。

记住在析构函数中delete[] index_pointer;

关于c++ - 如何在 C++ 类中创建私有(private)动态数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13480568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com