作为练习,我正在尝试创建一个充当简化数组类的myArray类。这是我的标题:
#ifndef myArray_h
#define myArray_h
typedef double ARRAY_ELEMENT_TYPE;
class myArray {
public:
//--constructors
myArray(int initMax);
// post: Allocate memory during pass by value
myArray(const myArray & source);
// post: Dynamically allocate memory during pass by value
//--destructor
~myArray();
// post: Memory allocated for my_data is deallocated.
//--modifier
void set(int subscript, ARRAY_ELEMENT_TYPE value);
// post: x[subscript] = value when subscript is in range.
// If not, an error message is displayed.
//--accessor
ARRAY_ELEMENT_TYPE sub(int subscript) const;
// post: x[subscript] is returned when subscript is in range.
// If not, display an error message and return [0].
private:
ARRAY_ELEMENT_TYPE* my_data;
int my_capacity;
};
#endif
这是我的实施:
#include "myArray.h"
#include <iostream>
#include <cstring>
using namespace std;
typedef double ARRAY_ELEMENT_TYPE;
//--constructors
myArray::myArray(int initMax)
{
my_capacity = initMax;
}
myArray::myArray(const myArray & source)
{
int i;
my_data = new ARRAY_ELEMENT_TYPE[source.my_capacity];
for(i=0; i < my_capacity; i++)
my_data[i] = source.sub(i);
}
//--destructor
myArray::~myArray()
{
delete [ ] my_data;
}
//--modifier
void myArray::set(int subscript, ARRAY_ELEMENT_TYPE value)
{
if(subscript > my_capacity - 1)
{
cout << "**Error: subscript " << subscript << " not in range 0.." << my_capacity-1 << ". The array is unchanged." << endl;
}
else
my_data[subscript] = value;
}
//--accessor
ARRAY_ELEMENT_TYPE myArray::sub(int subscript) const
{
if(subscript >= my_capacity)
{
cout << "**Error: subscript " << subscript << " not in range 0.." << my_capacity-1 << ". Returning first element." << endl;
cout << my_data[0];
}
else
{
return my_data[subscript];
}
}
我正在使用它作为测试驱动程序:
#include <iostream>
using namespace std;
typedef double ARRAY_ELEMENT_TYPE;
#include "myArray.h"
void show (const myArray & arrayCopy, int n)
{
for(int j = 0; j < n; j++)
cout << arrayCopy.sub(j) << endl;
}
int main()
{
int n = 6;
myArray a(6);
a.set(0, 1.1);
a.set(1, 2.2);
a.set(2, 3.3);
a.set(3, 4.4);
a.set(4, 5.5);
a.set(5, 6.6);
show(a, n);
cout << a.sub(11) << endl;
a.set(-1, -1.1);
return 0;
}
问题在于,当我运行它时,我什么也得不到,然后“按任意键继续......”提示。出了什么问题?
答案 0 :(得分:1)
myArray
构造函数不为my_data
分配内存。第一次调用set
时,它会尝试写入未初始化的指针。这会导致未定义的行为,但可能会发生崩溃。
您应该将构造函数更改为
myArray::myArray(int initMax)
{
my_capacity = initMax;
my_data = new ARRAY_ELEMENT_TYPE[my_capacity];
}
您还可以考虑使用代码的其他几个问题
在'set'中,测试
if(subscript > my_capacity - 1)
应该是
if(subscript < 0 || subscript > my_capacity - 1)
或者您可以将subscript
参数更改为类型unsigned int
。
在sub
中,行cout << my_data[0];
大概应为return my_data[0];
答案 1 :(得分:1)
myArray::myArray(int initMax)
{
my_capacity = initMax;
my_data = new ARRAY_ELEMENT_TYPE[my_capacity]; //You missed this
}
答案 2 :(得分:0)
除了在当前实现中缺少分配外,您还可以动态分配内存。不需要在堆上分配简单的数组类型。 std::array
集合完全符合您的要求。我想请你看一下它的实现例子(如果这只是一个学术练习)。如果这是用于生产代码库,请使用已编写和测试的内容。