构造函数中的动态内存分配
Dynamic memory allocation in constructor
我正在学习动态内存分配。我有以下类,其中"类 A"应该在构造函数中拥有一个动态分配的数组。还应修改复制构造函数和析构函数。这就是我到目前为止所拥有的...
#include <iostream>
#ifndef A_HH
#define A_HH
#include "B.hh"
class A {
public:
A() { B *array = new B[12];}
A(const A&) { /* Do not know what to put here..*/ }
~A() { delete[] array;}
private:
//B array[12] ; <- This is the array that I have to modify so it becomes dynamic.
B *array;
} ;
#endif
对于初学者,您的默认构造函数会用相同类型的局部变量覆盖成员变量"array",因此您希望默认构造函数如下所示:
A() { array = new B[12]; }
然后,复制构造函数可能需要将数组深层复制过来,但是对于一个简单的数组,您无法在运行时分辨数组大小。您需要移动到更智能的容器(例如 stl::vector(或存储大小,但朴素的复制构造函数如下所示:
A(const A& other)
{
array = new B[12];
for(int i=0;i<12;i++)
{
array[i] = other.array[i];
}
}
查看此代码:
#include <iostream>
using namespace std;
class MyArray{
public:
int* array;
int length;
MyArray(int length){ // constructor which takes length of array as argument
this->length = length;
this->array = new int[this->length];
for(int i=0; i<this->length; i++){
this->array[i] = i;
}
}
MyArray(const MyArray &obj){
this->length = obj.length;
this->array = new int[this->length];
for(int i=0; i<this->length; i++)
{
this->array[i] = obj.array[i];
}
}
~MyArray(){ // destructor
delete[] this->array;
}
void print(){ // test method for printing the array
for(int i=0; i<this->length; i++){
cout << this->array[i] << endl;
}
cout << endl;
}
private:
protected:
};
int main()
{
MyArray *array = new MyArray(10);
MyArray *array2 = new MyArray(*array); // call copy constructor
array->print();
array2->print();
delete array;
delete array2;
}
相关文章:
- Win32编译器选项和内存分配
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 当需要超过16GB的连续内存时,内存分配失败
- 尝试摆脱任何堆内存分配
- 以下代码执行哪种内存分配(动态或静态)?
- 开放 CV 中的动态内存分配,用于视频处理
- 为什么类和 main() 函数中也有动态内存分配
- 使用 NTAllocateVirtualMemory 和 GetProcAddress 的内存分配问题不起作用
- C++:矢量分配器行为、内存分配和智能指针
- 介于 [固定数组] 和 [带内存分配的指针] 之间的性能
- Linux C++ 中的页面对齐内存分配
- 整数内存分配/释放
- 将内存分配返回值强制转换为 TYPE 数组
- C++程序什么都不做,但瓦尔格林德显示内存分配
- 给定特定内存地址的数组的动态内存分配
- 如何完成内存分配
- 我刚刚了解了C++中的动态内存分配
- 在先前调用 string::find 后添加内存分配和内存集会导致它返回 npos.为什么?
- 对于堆上的页面对齐内存分配是否有任何优化或不同的 API?
- 无法删除布尔动态内存分配