-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;
}

但是赋值运算符呢?请参阅什么是三法则?

于 2013-10-13T17:31:29.037 回答
0

您的循环停止条件for在最后一个元素之后结束它(即您无法访问sam向量的第 4 个元素,因为只有三个元素)。

std::vector::at在这种情况下抛出std::out_of_range异常(参见:http ://en.cppreference.com/w/cpp/container/vector/at ),不是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 回答