-1

このベクター クラスがあり、クラスをテストするためのドライバーが提供されました。ほとんどは問題なく動作しているようですが、例外の部分に何か問題があると思います (完全には理解していません)。

クラス .cpp ファイルのコードは次のとおりです。

int myVector::at(int i)
    {
if(i<vsize)
    return array[i];
    throw 10;
    }

ここにドライバーコードがあります

#include "myVector.h"
#include <iostream>
using namespace std;

int main()
{
// Create a default vector (cap = 2)
myVector sam;

// push some data into sam
cout << "\nPushing three values into sam";
sam.push_back(21);
sam.push_back(31);
sam.push_back(41);

cout << "\nThe values in sam are: ";

// test for out of bounds condition here
for (int i = 0; i < sam.size( ) + 1; i++)
{
    try
    {
            cout << sam.at(i) << " ";
    }
    catch(int badIndex)
    {
        cout << "\nOut of bounds at index " << badIndex << endl;
    }
}
cout << "\n--------------\n";

// clear sam and display its size and capacity
sam.clear( );
cout << "\nsam has been cleared.";
cout << "\nSam's size is now " << sam.size( );
cout << "\nSam's capacity is now " << sam.capacity( ) << endl;  
cout << "---------------\n";

// Push 12 values into the vector - it should grow
cout << "\nPush 12 values into sam.";
for (int i = 0; i < 12; i++)
    sam.push_back(i);

cout << "\nSam's size is now " << sam.size( );
cout << "\nSam's capcacity is now " << sam.capacity( ) << endl;
cout << "---------------\n";

cout << "\nTest to see if contents are correct...";
// display the values in the vector
for (int i = 0; i < sam.size( ); i++)
{

    cout << sam.at(i) << " ";
}
cout << "\n--------------\n";

cout << "\n\nTest Complete...";

cout << endl;
system("PAUSE");
return 0;
}

どんな助けでも大歓迎です。ありがとう

4

2 に答える 2

1

あなたが提供したドライバー:

try {
    cout << sam.at(i) << " ";
}
catch(int badIndex) {
    cout << "\nOut of bounds at index " << badIndex << endl;
}

それがスローされることを期待していintます(少し奇妙なデザインですが、まあ...これはあなたのクラスを使用するコードです...)。の実装は次のat()ようになります。

int& myVector::at(int i) throw(int) {
    if (i < vsize)
        return array[i];
    throw i;
}

値によるスロー、参照によるキャッチという単純なルールに従うようにしてください。


また、ポインタがあることに注意してください。

private:
    int* array;

これは、コンストラクターとコピー コンストラクターで割り当てられ、デストラクタで解放される、動的に割り当てられたメモリを指します。

myVector::myVector(int i)
{
    ...
    array = new int[maxsize];
}
myVector::myVector(const myVector& v)//copy constructor 
{
    ...
    array =new int[maxsize];
}
myVector::~myVector()
{
    delete[] array;
}

しかし、代入演算子はどうですか? 3 のルールとは何ですか? を参照してください。

于 2013-10-13T17:31:29.037 に答える
0

ループの停止条件はfor、最後の要素の 1 つ後に終了します (つまり、要素samが 3 つしかないため、ベクトルの 4 番目の要素にアクセスできません)。

std::vector::atstd::out_of_rangeそのような状況で例外をスローします ( http://en.cppreference.com/w/cpp/container/vector/atを参照)。1 つではありませんint。したがって、例外処理部分を次のように変更する必要があります。

#include <exception>

try
{
        cout << sam.at(i) << " ";
}
catch(std::out_of_range exc)
{
    cout << "\nOut of bounds at index " << exc.what() << endl;
}
于 2013-10-13T17:35:29.287 に答える