如何在向量类中使用异常和指针
how to use exceptions and pointers in a vector class
我有这个向量类,我有一个驱动程序来测试这个类。大部分似乎都可以正常工作,但我认为例外部分有问题(我还没有完全理解)
这是类.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;
}
相关文章:
- 尝试使用智能指针时引发异常
- 获取指向派生类的指针在 C++ 中以运行时异常结束
- C++指针算术:对齐异常 (0x801)
- 如何避免自定义 STL 向量类的智能指针 delete[] 异常?
- free():在有效指针异常中-使用流读取巨大文件时
- 封送指向结构异常"cannot Read or Write protected memory"的指针数组的指针数组
- 将一个数组复制到函数内的另一个数组时的运行时指针异常
- dynamic_cast指针异常捕获
- 动态指针引用数组由三元运算符返回值,但有异常
- 异常未手动 - 这是空指针C++
- 启用优化时的堆栈指针比较异常
- 构造函数中的异常:init() 方法、指针、大型 try/catch 或
- 异常包括字符指针和整数指针
- 智能指针和构造函数异常
- 在Linux/GCC下,将NULL指针访问转换为C++异常
- 指向矩阵的指针在 c++ 中引发异常
- 函数指针中的C 异常规范
- 在OpenCV中调用stereoRectify会导致异常:帧指针无效
- 可以通过异常指针"duplicated"异常吗?
- 为什么在抛出异常指针时要通过引用使用 catch