如何在向量类中使用异常和指针

how to use exceptions and pointers in a vector class

本文关键字:异常 指针 向量      更新时间:2023-10-16

我有这个向量类,我有一个驱动程序来测试这个类。大部分似乎都可以正常工作,但我认为例外部分有问题(我还没有完全理解)

这是类.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 << "nnTest Complete...";
cout << endl;
system("PAUSE");
return 0;
}

任何帮助,不胜感激。谢谢

您提供的驱动程序:

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

但是赋值运算符呢?看看什么是三法则?

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

在这种情况下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;
}