我有这个矢量类,并且我提供了一个驱动程序来测试该类。大多数似乎工作正常,但我认为异常部分有一些问题(我还没有完全理解)
以下是类.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;
}
感谢任何帮助。感谢
答案 0 :(得分: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;
}
但 赋值运算符 怎么样?见What is The Rule of Three?
答案 1 :(得分: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;
}