![](/img/trans.png)
[英]How do you create a dynamic array for struct elements of different variable types for c++?
[英]How do you create a private dynamic array in a c++ class?
您好我在类中使用动态数组时遇到问题。 我被告知“类VectorDouble将有一个私有成员变量用于动态的双精度数组。” 我只是为这个程序编写头文件,但我没有超过它。 一旦达到容量,该类需要能够加倍。 这是我的代码:
#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的私有int成员。 我不确定那个成员是为了什么,但是如果你确实需要它,那么你必须将它命名为指针或指针。
记得delete[] index_pointer;
在你的析构函数中。
你应该使用std::vector<double>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.