1

演習として、簡略化された配列クラスとして機能するクラス 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;
}

問題は、これを実行すると、しばらく何も表示されず、「続行するには何かキーを押してください...」というプロンプトが表示されることです。何がうまくいかないのですか?

4

3 に答える 3